首页 > 解决方案 > PHP API REST:捕获所有值对象异常并将它们呈现为数组

问题描述

我正在使用值对象开发 PHP API REST。我有一些值对象,例如:ID、日期、名称等。当它们由于格式无效或其他原因导致构造失败时,会引发 InvalidArgumentException。

我如何“收集”所有异常以及当脚本停止时将它们发送到 json 响应中的“错误”数组中?

问题是我认为为每个值对象进行数百次 try catch 并不是最好的方法,而且我找不到在 try 块中捕获多个异常的方法。

可能抛出 InvalidArgumentException 的值对象

$authorID = new ID('dd'); // Must be an integer greather than 0 or null

我也想在实体的构造函数中传递这个 ValueObject

 new Insertable($authorID);

如果我有多个可能引发异常的 ValueObjects,我如何才能将它们全部捕获并将这些异常作为“错误”数组做出响应?

谢谢!

标签: phpapirestdomain-driven-designvalue-objects

解决方案


This is not especially elegant, but a possible solution. Just create a global $errors array and collect all messages.

$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();
}

At the end output them all

echo json_encode(['errors' => $errors], JSON_PRETTY_PRINT);

will give something like

{
    "errors": [
        "Author ID needs to be numeric",
        "Author ID needs to be numeric"
    ]
}

推荐阅读