我正在使用值对象开发一个PHP API REST。我有一些值对象,例如: ID、Date、Name等。当它们由于无效的格式或其他原因导致构造失败时,它会抛出一个InvalidArgumentException。
如何“收集”所有异常,以及当脚本停止时,在json响应中的"error“数组中发送它们?
问题是,我认为对每个值对象进行数百次try catch并不是最好的方法,而且我找不到在try块中捕获多个异常的方法。
可能引发InvalidArgumentException的值对象
$authorID = new ID('dd'); // Must be an integer greather than 0 or null我还希望在实体的构造函数中传递此ValueObject
new Insertable($authorID);如果我有多个可能抛出异常的ValueObjects,我如何捕获它们并以"error“数组的形式响应这些异常呢?
谢谢!
发布于 2020-09-21 01:27:48
这并不是特别优雅,但却是一种可能的解决方案。只需创建一个全局$errors数组并收集所有消息。
$errors = [];
try {
$authorID = new ID('dd');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}
// and collect some more
try {
$authorID = new ID('ff');
} catch(Exception $e) {
$errors[] = $e->getMessage();
}最后将它们全部输出
echo json_encode(['errors' => $errors], JSON_PRETTY_PRINT);会给出类似这样的东西
{
"errors": [
"Author ID needs to be numeric",
"Author ID needs to be numeric"
]
}发布于 2020-09-21 01:25:40
我们只需要使用一个try-catch块,因为它可以在一次go中处理多个错误/exception。示例:
try {
$x = 5;
//Statement 1
throw_if(x===5, new Exception('Some Message'));
//Statement 2
throw_if(x===2, new Exception('Some Message'));
//go ahead with your logic
} catch(Exception $e) {
$message = $e->getMessage();
//send error response here
} 如果你想收集所有的错误/exception并在错误响应中返回它们,那么就这么做吧。示例:
$errors = [];
try {
$x = 5;
//Statement 1
if($x===5) {
$errors['stmt1'] = 'Some Message';
}
//Statement 2
if($x===2) {
$errors['stmt2'] = 'Some Message';
}
if(count($errors) > 0) {
//return the $errors here as it contains all error(S)/exception(s)
}
//go ahead with your logic
} catch(Exception $e) {
$message = $e->getMessage();
//Any unknown error/exception will be catches here
} https://stackoverflow.com/questions/63981570
复制相似问题