Learn How to Send an Email on Error Exceptions

Published on by

Learn How to Send an Email on Error Exceptions image

You’ve created a new Laravel app for your client and deployed it on the production server. Everything was working fine till a customer has a problem with the app because of some buggy code. He immediately leaves the app, and the same thing happens with multiple customers before you know about the bug. You fix the bug, and then everything is on track.

But what if you were notified immediately through e-mail (or another service) about the bug and you fix it ASAP. In Laravel, this can be done easily and in this post, we’re going to learn how.

In Laravel, all exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We’re only interested in report method; it is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method simply passes the exception to the base class where the exception is logged. However, we can use it to send an email to developers about the exception.

/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Emails.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
if ($this->shouldReport($exception)) {
$this->sendEmail($exception); // sends an email
}
 
return parent::report($exception);
}
 
/**
* Sends an email to the developer about the exception.
*
* @param \Exception $exception
* @return void
*/
public function sendEmail(Exception $exception)
{
// sending email
}

Here we are using shouldReport method to ignore exceptions which are listed in the $dontReport property of the exception handler.

Each type of email sent by the application is represented as a “mailable” class in Laravel. So, we need to create our mailable class using the make:mail command:

$ php artisan make:mail ExceptionOccured

This will create a class ExceptionOccured in the app/Mail directory.

Merely sending the mail will not solve the problem. We need the full stack trace of the exception. And for that, we can use the Symfony’s Debug component.

public function sendEmail(Exception $exception)
{
try {
$e = FlattenException::create($exception);
 
$handler = new SymfonyExceptionHandler();
 
$html = $handler->getHtml($e);
 
Mail::to('developer@gmail.com')->send(new ExceptionOccured($html));
} catch (Exception $ex) {
dd($ex);
}
}

Make sure you add the following code at the top of the file:

use Mail;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use App\Mail\ExceptionOccured;

Note—We have used the try block to avoid the infinite loop if the mail command fails.

Then, in your ExceptionOccured mailer class:

<?php
 
namespace App\Mail;
 
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
 
class ExceptionOccured extends Mailable
{
use Queueable, SerializesModels;
 
/**
* The body of the message.
*
* @var string
*/
public $content;
 
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($content)
{
$this->content = $content;
}
 
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.exception')
->with('content', $this->content);
}
}

Add the following code in your emails.exception view file:

{!! $content !!}

Now, whenever an exception is thrown in your application, you will receive an email with full stack trace. Cool!

I have created a Laravel package named squareboat/sneaker to do all this cumbersome work for you so you can concentrate on solving the bug.

Some of the features of the sneaker are: – On/off emailing using .env file. – Customizing the email body. – Ignoring the exception generated by bots.

and more to come.

If you want the complete source code for this, I’m more than happy to share it and you can find the source code on Github

Amit Gupta photo

Love to code, and have fun when helping others. At the moment I'm a big fan of Laravel framework and I am now what some would refer to as an "evangelist". I love to help others learn more about Laravel and get them started on the road to success. I hang out a LOT in #laravel on Stackoverflow. I've been developing the web and mobile apps and what not for roughly 2 years now and I am learning more all the time.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
PHPStan 2.0 is Here image

PHPStan 2.0 is Here

Read article
Run multiple CLI commands locally at once with Solo for Laravel image

Run multiple CLI commands locally at once with Solo for Laravel

Read article
Securing Laravel Applications with Stephen Rees-Carter image

Securing Laravel Applications with Stephen Rees-Carter

Read article
Laravel on any Developer Machine with Gitpod image

Laravel on any Developer Machine with Gitpod

Read article
Build your slide deck in Laravel with Simple Slides image

Build your slide deck in Laravel with Simple Slides

Read article
Lazy JSON Pages is a JSON API Scraper for PHP image

Lazy JSON Pages is a JSON API Scraper for PHP

Read article