在AJAX请求我目前正在处理错误类似于这样的方式:PHP AJAX错误处理
try {
// code
if (some_error_condition) {
throw new \Exception('error');
}
// other code
if (some_other_error_condition) {
throw new \Exception('other error');
}
// more code
$response = array(
'success' => TRUE,
'data' => 'stuff here'
);
} catch (Exception $e) {
$response = array(
'success' => FALSE,
'error' => $e->getMessage()
);
}
header('Content-Type: application/json');
echo json_encode($response);
我的问题是:有没有更好的方式来处理比这个多可能的错误情况,同时仍坚持干的原则?我认为这种方法比巨大的嵌套if/else错误更加清晰和易于遵循,但它有点让人想起goto
代码。
也许是一种面向对象的方式?
你使用任何库吗?大多数框架(jQuery,Mootools等)都会有onSuccess/onFailure方法,您可以使用它们而无需重新发明轮子。 – julio 2012-01-05 21:19:35
@julio:我对如何处理PHP中的错误感兴趣,而不是JavaScript。 – FtDRbwLXw6 2012-01-05 21:20:43
看看[这里](http://stackoverflow.com/questions/8698057/jquery-ajax-fail-and-return-exception/8698477#8698477) – devdRew 2012-01-05 21:20:55