Error Reporting gives you insight into which bugs are the most severe or frequent, allowing you to prioritize bug fixes based on facts, not guesswork.
Laravel is a powerful and one of the best MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. It facilitates developers by saving huge time and helps reduce thinking and planning to develop the entire website from scratch.
Whenever we are planning to deploy Laravel application on production server, we test aggressively and try to find out bugs that may create nightmare for clients as well as for developers. Once we are done with testing we turn debug/error logs off for display as actual users are never shown the behind process.
Everything was working fine after we deployed app on production server till customer founds a problem while accessing app due to bug and he/she immediately leaves the application. This can happen to multiple customers until app developers found the same bug and resolves it. This can be very bitter experience for customers and the client will be also be not happy with the service provided.
Now just think that if you were notified immediately through e-mail about the bug the very first time any customer faced and you fix it ASAP. Laravel provides this feature to send email whenever error occurs on application so that website downtime is much less and minimum customer faces the issue. Let's see how to do that in Laravel.
In Laravel application , all exceptions are handled by the App\Exceptions\Handler
class which is by default present in your project directory. This class contains two methods: report and
render
. We will only use report
method as it is used to log exceptions and send then to email or any other service. By default, the report method simply passes the exception to the base class where the exception is logged. We will modify this method to send error logs to developer or any other email.
Now I am going to show you how you can send error exception mail in your laravel app. Just follow the below steps and you are ON for receiving error logs on e-mail.
1. Create Mail Class using make:mail command
The below command will create a class ExceptionOccured in the app/Mail
directory.
php artisan make:mail ExceptionOccured
After mail class is created, change the code as given below. This will return the error returned to a view file which we will create in next step.
namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class ExceptionOccured extends Mailable { use Queueable, SerializesModels; public $content; /** * Create a new message instance. * * @return void */ public function __construct() { $this->content = $content; } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.exception') ->with('content', $this->content); } }
2. Create Email View File
Now Let's create a new view file inside the resouces/views/emails folder with name exception.blade.php. and the below-given code in newly created file. We will just echo the variable passed from Mail class we created in previous step.
{!! $content !!}
3. Send Error Exception Mail from Handler file
Let's Go to App\Exceptions\Handler file and update the below code into your file.
namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Log; use Throwable; use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer; use Symfony\Component\ErrorHandler\Exception\FlattenException; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * @param \Throwable $exception * @return void * * @throws \Exception */ public function report(Throwable $exception) { // emails.exception is the template of your email // it will have access to the $error that we are passing below if ($this->shouldReport($exception)) { $this->sendEmail($exception); // sends an email } return parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Throwable $exception * @return \Symfony\Component\HttpFoundation\Response * * @throws \Throwable */ public function render($request, Throwable $exception) { return parent::render($request, $exception); } public function sendEmail(Throwable $exception) { try { $e = FlattenException::create($exception); $handler = new HtmlErrorRenderer(true); // boolean, true raises debug flag... $css = $handler->getStylesheet(); $content = $handler->getBody($e); \Mail::send('emails.exception', compact('css','content'), function ($message) { $message->to(['youremail1@gmail.com','youremail2@gmail.com']) ->subject('Exception: ' . \Request::fullUrl()); }); } catch (Throwable $exception) { Log::error($exception); } } }
We have added sendEmail function which is executed when any exception is reported in handler file. You will receive an email with full information about the errors. You need to replace email id in place of "youremail1@gmail.com" and "youremail2@gmail.com". Also change the subject as per your requirement.
That's it and you are ready to receive error log instantly when occurred in Laravel Application.
Bonus Tip - Add custom 500 ERROR Page which we be displayed to customer when any error is generated.
Create new file 500.blade.php inside resources/views/errors directory. Laravel by default returns custom file which matches the error code. As we want custom file for exception we will create with this name. You can also create custom files for other errors such as 404(Page not found) .
Conclusion
In this tutorial, you have learnt step by step process on how to send error exceptions to mail in Laravel Application.
If you were immediately informed via e-mail about the bug than you can fix it ASAP and reduce application downtime and create a better experience for website/application visitors.
Do you plan to develop Feature Rich Laravel Application or want any customization in Existing Laravel Application?
Our Laravel Development team and I will be ready to roll out your plan into reality. Feel free to bring us your idea and get a free quote.
Sahil is a highly skilled and dedicated Salesforce Certified Platform Developer with a passion for creating efficient and innovative solutions within the Salesforce ecosystem. With an insatiable curiosity and a relentless drive for excellence, he has become a go-to expert in developing custom applications and functionalities on the Salesforce platform.
Comments are closed.