How can I be notified by e-mail when a critical error occurs in a Laravel application?

RMAG news

Although Laravel manages logs efficiently, it can sometimes be crucial to keep a close eye on errors during the development of certain projects. This tip will enable you to receive an e-mail as soon as a critical error occurs on your server. It is important to note that it is recommended to send only critical errors to avoid saturating your inbox.
The simplest approach (in my opinion) is to use bug-tracking software such as Sentry (or equivalent); this will help regulate notifications. But what if I don’t want these services? I can do my own thing.

Creation of the ExceptionMail mail class

Run this command in your Laravel project:

php artisan make:mail ExceptionMail

Once the mail class is created, we’ll modify it. Instead of creating a separate view, I’ll inject HTML content directly.

namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesEnvelope;
use IlluminateQueueSerializesModels;

class ExceptionMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct(private string $htmlString)
{
//
}
public function envelope(): Envelope
{
return new Envelope(
subject: ‘A critical error occurred’
);
}

public function content(): Content
{
return new Content(
htmlString: $this->htmlString
);
}
}

Sending the Email

In the app/Exceptions/Handler.php class, you’ll find Laravel’s base exception handling class. Let’s add a private sendMail method to this class and called it in the rergister method.

namespace AppExceptions;
use AppMailExceptionMail;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use IlluminateSupportFacadesMail;
use Throwable;

class Handler extends ExceptionHandler
{
public function register(): void
{
$this->reportable(function (Throwable $e) {
$this->sendMail($e);
});
}

private function sendMail(Throwable $e)
{
if (App::isLocal()) {
return;
}

//Developer emails
$emails = [“developers@email.coms”, “etc@etc.com”];

$htmlStr = “An error occurred while processing the request. Here is the error”;
//You should normally return the file, the line, the code and the message, so that you have an idea of what it’s about without consulting the log
$htmlStr .= $e->getMessage();
try {
Mail::to($emails)->send(new ExceptionMail($htmlStr));
} catch (Throwable $th) {
//Your code
}
}
}

Note:

I used Laravel 9; please adapt according to your version.
Ensure not to send all exceptions, but only critical errors.
It’s not advisable to send email notifications in production mode.

If you want to simplify form validation in your Laravel projects and save time, I recommend trying out this library Trivule.

Follow me on Twitter and Dev Community for more tips and shares.

Leave a Reply

Your email address will not be published. Required fields are marked *