Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP AJAX错误处理_Php_Ajax_Error Handling - Fatal编程技术网

PHP AJAX错误处理

PHP AJAX错误处理,php,ajax,error-handling,Php,Ajax,Error Handling,目前,我在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

目前,我在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
code


也许是一种面向对象的方法?

它对我来说是完全有效的解决方案,只是您可以为异常使用不同的异常类,并将实际逻辑封装在某个对象中,如

class Handler {
      //this function executes code and throws exception - no error handling logic.
     public static function doSomeCode() { 
         (...)
         return $response;
     }
}

try {
    $response = Handler::doSomeCode();
    renderResponse();
} catch (SomeError $e) {
     $err = 'some error';
     renderError($err);
} catch (Exception $e) {
     header('500 Internal Server Error'); //this is pseudo code!
} 

您的异常类(除了泛型异常)可以处理呈现错误,异常类将触发500(它永远不会发生)。通过这种方式,您可以将实际代码执行与错误处理分开,并且在适当的例外情况下,对象模型不会重复错误处理。

您是否使用任何库?大多数框架(jQuery、Mootools等)都有onSuccess/onFailure方法,您可以使用这些方法,而无需重新发明轮子。@julio:我感兴趣的是如何处理PHP中的错误,而不是JavaScript。look@devdRew:谢谢,但这与我的要求并不相关。我对如何构造PHP代码的最佳实践感兴趣,使其能够灵活有效地处理多个错误条件。有趣。对于每个相关的HTTP响应代码(未授权、错误请求等),您是否有不同的自定义
异常
类?还是只使用一个来处理所有代码?这取决于错误处理逻辑是否不同-只要相同,我将使用一个异常类(即HttpException),当逻辑不同时,您始终可以重构以分离它。