How to return an HTTP 500 code on any error, no matter what

后端 未结 7 845
无人及你
无人及你 2020-12-09 14:35

I\'m writing an authentication script in PHP, to be called as an API, that needs to return 200only in the case that it approves the request, and403(Forbid

相关标签:
7条回答
  • 2020-12-09 15:17

    On the php page for set_error_handler() you can find a comment by smp at ncoastsoft dot com posted on 08-Sep-2003 10:28 which exlpains how to even catch fatal errors (which you can normally not catch with a custom error handler. I changed the code for you needs:

    error_reporting(E_ALL);
    ini_set('display_errors', 'on');
    
    function fatal_error_handler($buffer) {
        header('HTTP/1.1 500 Internal Server Error');
        exit(0);
    }
    
    function handle_error ($errno, $errstr, $errfile, $errline){
        header('HTTP/1.1 500 Internal Server Error');
        exit(0);
    }
    
    ob_start("fatal_error_handler");
    set_error_handler("handle_error");
    
    //would normally cause a fatal error, but instead our output handler will be called allowing us to handle the error.
    somefunction();
    ob_end_flush();
    

    This shold catch the fatal error of the non existing function. It than returns a 500 and stops the execution of the rest of the script.

    0 讨论(0)
提交回复
热议问题