php - 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,我如何才能将它们全部捕获并将这些异常作为“错误”数组做出响应?
谢谢!
解决方案
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"
]
}
推荐阅读
- css - 无法更改 Bootstrap 5 轮播指示器边框半径
- android - 如何实现一个中心化的事件系统?Android - 实时数据
- intune - inTune APP 应用程序已安装但有更新版本可用?
- c# - MemoryStream closes when passing it as a parameter to another method with a local function
- visual-studio - Visual Studio 拒绝插入 DLL 参考
- verilog - ALU NOOP 案例推断闩锁:这可以吗?
- apache-spark - Pyspark 高阶函数 - 一次在结构数组中求和 2 个值?
- docker - 外部 IP 是
在 Kubernetes 服务中 - javascript - 仅在 Android React-Native (expo) 中的行首图像定位
- javascript - Vue - 仅对 v-for 数组中新添加的元素执行操作