Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle php notices, warnings and errors in REST api?

In REST API a 200 response show a successful operation. PHP by default output the error message directly in the response body without changing response code. In SPAs, the response text is not directly visible to user. So when the application does not work as expected I have check response body through FireBug to check for possible PHP exceptions (which cause invalid json response). Is there any way to send a specific HTTP code on all PHP errors?

Is there any way to change the HTTP response code according to existence of any PHP errors? Or, is it possible to grab the error text and send it in json format in a hassle-free way. (in development phase)

Update: Exception Catching (try/catch/final) is not what I am looking for.

like image 742
Handsome Nerd Avatar asked Apr 30 '15 05:04

Handsome Nerd


People also ask

How does PHP handle notice error?

By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php. ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.

How do you handle errors in REST API?

3.1. The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter. 401 Unauthorized – client failed to authenticate with the server.

How do I hide warnings and notices in PHP?

In the current file, search for the line of code error_reporting. There will be a line of Default Value: E_ALL as shown below: Replace this line of code with Default Value: E_ALL & ~E_NOTICE. It will display all the errors except for the notices.

How do I turn off PHP error reporting?

To turn off or disable error reporting in PHP, set the value to zero. For example, use the code snippet: <? php error_reporting(0); ?>


4 Answers

In Yii Framework, Handling such issues very efficiently.

They have used PHP's set_exception_handler('exceptionHandlerFunction') and set_error_handler('errorHandlerFunction') function to handle all types of Exceptions and Errors (Warnings, Notice) repectively.

On FATAL Error, register_shutdown_function('fatalHandlerFunction')

Now, for display purpose, Yii is doing very efficiently.

In error/exception/fatal handler function, It's upto configuration to either throw error to client side OR display well formatted error.

If want to display well formatted then, Yii is transfering route to SystemController's Error action.

You can also go through with How Yii Handling Errors.

Hope it helps !!

like image 200
Sanjay Mohnani Avatar answered Sep 20 '22 22:09

Sanjay Mohnani


set_error_handler function is what I missed. I came up with the following code. Any better answer is welcomed.

function jsonErrorHandler()
{
   if (error_reporting()) {

        http_response_code(500);
        header('Content-Type: application/json; charset=utf-8');
        $response = array_combine(['errno', 'errstr', 'errfile', 'errline', 'errcontext'], func_get_args());
        die(json_encode($response));

  }
}

set_error_handler('jsonErrorHandler');
like image 21
Handsome Nerd Avatar answered Oct 09 '22 21:10

Handsome Nerd


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 );

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 );

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" );

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' );

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

like image 11
Danijel Avatar answered Oct 09 '22 20:10

Danijel


Of course you can change HTTP status in PHP:

<?php 
   header("HTTP/1.1 502 Bad Gateway");
?> 

You could change the message and the code, but you must to be careful with standard codes

like image 11
jpintor Avatar answered Oct 09 '22 20:10

jpintor