PHP API REST:捕获所有值对象异常并将其呈现为数组

问题描述

我正在使用Value Objects开发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);

如果我有多个可能引发异常的ValueObject,如何捕获所有异常并以“错误”数组的形式对这些异常做出响应?

谢谢!

解决方法

这不是特别优雅,但可能的解决方案。只需创建一个全局$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"
    ]
}
,

我们只需要使用一个try-catch块,因为它可以一次处理多个错误/异常。示例:

async function countAndUpdate() {
  const count = await User.countDocuments({age:{$gte:5}}

  await StatChartMonitor.findByIdAndUpdate(id,{ $set: { viewCount: count } })
}

如果您要收集所有错误/异常并以错误响应将其全部返回,则可以这样做。示例:

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
}