What Is Error Handling In Laravel FrameWork With Example

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We'll dive deeper into this class throughout this documentation.

What Is Error Handling In Laravel FrameWork With Example

Configuration
 

The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users.

The Report Method
 

All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We'll examine each of these methods in detail. The report method is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, the report method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.

For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator:

   /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Flare, Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $exception
     * @return void
     */
    public function report(Throwable $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    parent::report($exception);
}


Global Log Context

If available, Laravel automatically adds the current user's ID to every exception's log message as contextual data. You may define your own global contextual data by overriding the context method of your application's App\Exceptions\Handler class. This information will be included in every exception's log message written by your application:

 /**
     * Get the default context variables for logging.
     *
     * @return array
     */
    protected function context()
{
    return array_merge(parent::context(), [
        'foo' => 'bar',
    ]);
}


The report Helper

Sometimes you may need to report an exception but continue handling the current request. The report helper function allows you to quickly report an exception using your exception handler's report method without rendering an error page:
 

public function isValid($value)
{
    try {
        // Validate the value...
    } catch (Throwable $e) {
        report($e);

        return false;
    }
}


Ignoring Exceptions By Type

The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:
 

 /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,
];


The Render Method

The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Throwable $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

    return parent::render($request, $exception);
}


Reportable & Renderable Exceptions

Instead of type-checking exceptions in the exception handler's report and render methods, you may define report and render methods directly on your custom exception. When these methods exist, they will be called automatically by the framework:

<?php

namespace App\Exceptions;

use Exception;

class RenderException extends Exception
{
    /**
     * Report the exception.
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response(...);
    }
}

 

Learn in detail about error handling:

  • For new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis.

  • When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application.

    app\config\app.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Name
    |--------------------------------------------------------------------------
    |
    | This value is the name of your application. This value is used when the
    | framework needs to place the application's name in a notification or
    | any other location as required by the application or its packages.
    |
    */

    'name' => env('APP_NAME', 'Laravel'),

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services the application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG', false),

   
];


By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces.

 

The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file.

  • The value is set to true in a local development environment and is set to false in a production environment.

  • If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.


Error Log
 

Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel −

  • Laravel uses monolog PHP logging library.

  • The logging parameters used for error tracking are single, daily, syslog and errorlog.

  • For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −

'log' => env('APP_LOG',’daily’),


If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value.

‘log_max_files’ => 25;


Severity Levels

As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below 

'log_level' => env('APP_LOG_LEVEL', 'error')

Related Post