Exception Handling Methods

While doing a project, it is common to come across various errors and exceptions. Luckily for us, error and exception handling is already configured in Laravel. App\Exceptions\Handler class controls all the exceptions and then renders it back to the user.

In this article, we’ll go through these exception-handling methods. App\Exceptions\Handler has two methods: report and render. Let’s discuss these two methods below:

Report Method

The report method helps to log exceptions or send them to external services like Flare, Bugsnag, or Sentry. This method passes the exception to the base class where the exception is logged by default. Laravel also provides freedom for users to log exceptions as per their wish.

You can use the PHP instanceof operator to report different exceptions differently:

/**
 * 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

Users can define their global contextual data by changing context method which is in App\Exceptions\Handler class.

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

Report Helper

There may be cases where the user may want to report exceptions but also continue handling the current requests. For resolving this issue, the report helper function comes in handy. Basically what this function does is it reports the exception without displaying the error page.

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

        return false;
    }
}

Ignore Exception by Its Type

There may be times when one wants to ignore some exceptions. $dontReport is an array that consists of exception types that will not be logged in. Common examples of this are exceptions resulting from 404.

Here is how you declare $dontReport:

/**
 * 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,
];

Render Method

render method converts exceptions into the form of the HTTP response to the browser. The base class generates a response by default but users can also check the nature of an exception to return their 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 and Renderable Exception

This is a custom type of exception in which the user can define report and render. Here is a simple example of how you can do it:

<?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(...);
    }
}

These are the basics of exception handling in Laravel however you can extend further knowledge from Laravel’s official documentation.

Also, go through other various tutorials by clicking here.

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment