且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理REST API中的PHP通知,警告和错误?

更新时间:2022-06-20 06:19:58

例如,假设您只关心致命的运行时错误,致命的编译时错误和运行时警告.通过 error_reporting()函数将错误报告设置为所需的水平.>

Let say, for example, that you are only concerned about fatal run-time errors, fatal compile-time errors and run-time warnings. Set the error reporting to desired level with error_reporting() function.

error_reporting( E_ERROR | E_COMPILE_ERROR | E_WARNING );

由于用户定义的错误处理程序(下面稍后介绍)无法处理致命错误,因此仍然会显示致命错误消息.为避免这种情况,请使用 ini_set()函数并设置 display_errors归零.

Since user-defined error handler ( later below ) can't handle fatal errors, fatal error messages will still be displayed. To avoid that use ini_set() function and set the display_errors to zero.

ini_set( 'display_errors', 0 );

现在使用 set_error_handler()创建自定义错误处理程序为指定的错误类型完全绕过PHP错误处理程序(不适用于致命错误).

Now create a custom error handler with set_error_handler() to completely bypass PHP error handler for the error types specified ( does not apply to fatal errors ).

/* The following error types cannot be handled with a user defined function: 
 *  E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING
 * The standard PHP error handler is completely bypassed for the error types specified
 *  unless the callback function returns FALSE.
 */
function exception_error_handler( $severity, $message, $file, $line ) 
{
    if ( !( error_reporting() & $severity ) ) {
        // This error code is not included in error_reporting
        return;
    }

    // code for handling errors
}
set_error_handler( "exception_error_handler" );

在关闭时可以使用 register_shutdown_function()处理致命错误.>.关闭处理程序是在脚本完成后执行的,或者被终止(这也适用于error).我们需要获取有关最近发生的错误的信息( error_get_last()),下一步是检查这是否是我们跟踪的错误类型(这里并没有真正需要的错误,因为不会触发在 error_reporting 中未指定的错误,但是会触发该错误)可以用来过滤错误),最后,调用异常处理程序.

Fatal errors can be handled on shutdown with register_shutdown_function(). Shutdown handler is executed after the script is done, or is terminated ( this also applies for errors ). We need to get the information about the last error that occurred ( error_get_last() ), next is to check if this is the type of error that we track ( that it is not really needed here since errors that are not specified in error_reporting won't be triggered, but it can be useful to filter errors ), and lastly, call to exception handler.

function fatal_error_shutdown() 
{
    $last_error = error_get_last();
    if ( error_reporting() & $last_error['type'] )
        call_user_func_array( 'exception_error_handler', $last_error );
}
register_shutdown_function( 'fatal_error_shutdown' );

现在,您可以使用自定义异常处理程序来捕获未处理的异常(包括致命异常)并强制响应代码(使用 header()函数).

Now you can use custom exception handler to catch unhandled exceptions ( including fatal ones ) and to force the response code ( with header() function ).