我已经为这个问题挣扎了一段时间。我想在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响应中失败的项目,并通知用户。
我不确定这是最好的做法,还是有更好的方法?有没有更好的方法可以在不中止循环的情况下向客户端返回错误?
一些背景信息:我主要希望在向数据库添加数据时使用此功能。
如果您真的想从Exceptions向用户返回原始消息,请将带有$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);
但最好用自己的错误消息编写自己的验证。