我一直在努力解决这个问题。我想在我的foreach循环中捕获任何异常并继续循环遍历任何其他数据,但我还想让用户知道通过客户端失败了什么。所有对我的函数的调用都是通过ajax调用完成的。
为此我一直在使用以下内容:
$errors = array();
foreach ($form as $index => $data) {
try{
//continue, item has been processed
}catch(exception $e){
//add some data to the errors array
array_push($data, $errors);
}
}
return Response::json($errors);
这允许我在我的ajax响应中获取失败的项目并通知用户。
我不确定这是最佳做法还是有更好的方法来做到这一点?有没有更好的方法将错误返回到客户端而不中止循环?
一些背景信息: 我在将数据添加到数据库时,大部分都希望使用它。
答案 0 :(得分:0)
如果您确实要将原始邮件从“例外”返回给用户,请将带有$data['error'] = $e->getMessage();
的邮件附加到您的数据阵列,例如
$errors = array();
foreach ($form as $index => $data) {
try{
//continue, item has been processed
}catch(exception $e){
// append exception message to data
$data['error'] = $e->getMessage();
//add some data to the errors array
array_push($data, $errors);
}
}
return Response::json($errors);
但最好用自己的错误消息编写自己的验证。