Error Handling in Laravel

1
10496

Today we will be going through Error Handling in this Error Handling in Laravel tutorial.

  • Error handling terms to handle any errors that occur at runtime in an application and do not allow it to close abruptly.
  • PHP has uncaught exceptions, fatal errors, caught exceptions and non-fatal errors which can be handled successfully.
    • Tracing an error in Laravel:
      • Let us first see the error handling code in laravel:

      • Here we see that if an error occurs the ErrorException class will be thrown to handle it.
      • But here we have a condition to throw errors. The condition is
        if (error_reporting() & $level)
      • Here the condition indicates that “handle the error if it is an error that PHP would report”
      • But error_reporting in the file specified above i.e. vendor/laravel/framework/src/Illuminate/Exception/Handler.php is given as error_reporting(-1)
      • Here -1 indicates that show all PHP errors.
    • Tracing an Exception:
      • By default the app/start/global.php file contains an error handler for all exceptions.
      • App::error() is used to handle simple errors.
      • Let us see the most basic error handler:

      • This is the most basic exception handler which handles all errors.
      • You can even specify more handlers of your own.
      • Handlers are based on the type of the exception they handle. For example, we can create handlers that only handle runtime exceptions etc.
      • If an exception handler returns a response then that response will be sent to the browser and no other error handlers will be called.
      • Let us see an example of an exception handler that returns a response:

      • To handle fatal errors you can use App::fatal method as shown below:

      • We have many times come across the HTTP errors like “page not found” error (404), “unauthorized error” error (401) etc. These errors can be handled using App::abort() method.
      • Let us see an example:

      • You can even specify a message in it which is an optional parameter. Example is shown below:

    • An important thing is that if you have many exception handlers, you need to specify them in an order from most generic to most specific. So for the handler that handles all exceptions of type Exception should be defined before custom exceptions.
    • Another thing, you can place your error handling code anywhere you want, there is no special restriction for this in Laravel.
    • You can place it in the start/global.php file or you can create another errors.php file in the app folder to write error handlers and then require the file from start/global.php file.

 

Thus we learned few important things to be used while performing error handling in this Error Handling in Laravel tutorial.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here