Send Email Alert to Admin when Error Exceptions occurs in Laravel

It's very tedious for a developer to check error logs every day and make sure that everything is running fine. But you can reduce this daily overhead by creating simple developer notifications to Admin Mail or Slack for example.

1. Handle Exceptions in Laravel Handler

There is default Handler for all these exceptions at app\Exceptions\Handler.php in Laravel 8. We handled the situation in reportable callback.

<?php

namespace App\Exceptions;

use App\Jobs\JobDevNotification;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    .
    .
    .
    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            // Create Notification Data
            $exception = [
                "name" => get_class($e),
                "message" => $e->getMessage(),
                "file" => $e->getFile(),
                "line" => $e->getLine(),
            ];

            // Create a Job for Notification which will run after 5 seconds.
            $job = (new JobDevNotification($exception))->delay(5);

            // Dispatch Job and continue
            dispatch($job);
        });
    }
}

2. Create Mail for Alert

Create the Mail app\Mail\ErrorAlert.php in Laravel using below command. Refer Mail documentation on https://laravel.com/docs/8.x/mail

php artisan make:mail ErrorAlert
<?php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ErrorAlert extends Mailable
{
    use Queueable, SerializesModels;

    public $exception;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($exception)
    {
        $this->exception = $exception;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('system@example.com', 'System')->subject("Error Alert on Server")
                ->view('emails.error_alert');
    }
}

You will also need a resources\views\emails\error_alert.blade.php to format a mail. Here you can directly use $exception variable as it is set public in ErrorAlert.php.

Hello Admin,<br><br>

There is a <b>{{ $exception['name'] }}</b> on Laravel Server.<br><br>

<b>Error</b>: {{ $exception['message'] }}<br><br>

<b>File</b>: {{ $exception['file'].":".$exception['line'] }}<br><br>

<b>Time</b> {{ date("Y-m-d H:i:s") }}<br><br>

Please do the needful.

3. Create Database Queue to process Jobs in background

Now to run the Jobs in background we need to setup a database queue drivers. So we will update .env as below. Refer Queue documentation on https://laravel.com/docs/8.x/queues.

QUEUE_CONNECTION=database

Create the Queue Table in Database with following commands

$ php artisan queue:table
Migration created successfully!

$ php artisan migrate
Migrating: 2021_08_26_180839_create_jobs_table
Migrated:  2021_08_26_180839_create_jobs_table (52.85ms)

4. Create Job for Alert

Let's create a simple Job app\Jobs\JobDevNotification.php. Creating Job will make sure that your ongoing operations will not be affected.

<?php

namespace App\Jobs;

use App\Mail\ErrorAlert;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

/**
 * Developer Notification Job
 */
class JobDevNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $exception = [];

    /**
     * Create a new job instance.
     *
     * @param array $exception
     * @return void
     */
    public function __construct($exception)
    {
        $this->exception = $exception;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {
        // Send Mail
        Mail::to("admin@example.com")->send(new ErrorAlert($this->exception));
    }
}

5. Start Queue, Setup SMTP & Done

php artisan queue:listen

Now update you .env file for SMTP Gateway Details and you are good to go!

Find code for this article on https://github.com/gdbhosale/Laravel-Exception-Alerts

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.