TUTORIAL: How to add custom application context data to Laravel Exceptions

328 2

This post is also available in: Português

In any web application, when an Exception is raised, is important for the developer to know more about that exception as well as the context where it was raised in order to efficiently debug that exception. For years Laravel automatically added some global context to Exceptions log messages as contextual data. If the user is authenticated, it’s user ID is automatically included in the log message. You could also add custom global exception context to the log by adding the following method to your application’s App\Exceptions\Handler:

protected function context()
{
    return array_merge(parent::context(), [
        'foo' => 'bar',
    ]);
}

But now, since Laravel version 8.30.0, released yesterday, you can also add custom Exception context to every Exception in your application. Suppose you have a StudentAttendanceNotFoundException that is raised when a user try to view a profile of an nonexistent student on your system. That way, you can now add the student ID and the subject ID in the log, via the Exception Log Context.

To add this custom Exception Log Context to your Laravel exception, simple define a method named context inside your specific exception class which should return an array. The data on this array, as well as the data of global exception context, will be included on the log message every time that exception is raised:

<?php

namespace App\Exceptions;

use Exception;

class StudentAttendanceNotFoundException extends Exception
{
    // ...

    public function context(): array
    {
        return [
            'student_id' => $this->studentId,
            'subject_id' => $this->subjectId
        ];
    }
}

If you want to start using this functionality, just update your project to the latest Laravel release.

(Visited 274 times, 1 visits today)

Elisio Leonardo

Elisio Leonardo is an experienced Web Developer, Solutions Architect, Digital Marketing Expert, and content producer with a passion for technology, artificial intelligence, web development, and entertainment. With nearly 15 years of writing engaging content on technology and entertainment, particularly Comic Book Movies, Elisio has become a trusted source of information in the digital landscape.