Lesson 8 – Error Handling in Laravel

As Laravel is a powerful PHP framework, it also enables you to find and handle errors and exceptions rather easily. In fact, Laravel has a dedicated file handler.php to take care of these kinds of problems. The path to the file is app\exceptions\handler.php and it contains two functions by default, the Report and the Render. We will only use the first function for the sack of explanation in this lesson.

The report function sends the exceptions to a third party service or logs them in the base class. However, you can log these exceptions wherever and howsoever you want.

READ ALSO
Lesson 9 – Events and Listeners

Report function essentially does nothing more than forwarding the exceptions. If you want to perform task based on the errors, you can add a business logic to the function as shown in the following example. We are actually sending an email containing the error information in this example.

public function report(Exception $e)
{
 if ($e instanceof \Exception) {
 // Fetch the error information we would like to
 // send to the view for emailing
 $error['file'] = $e->getFile();
 $error['code'] = $e->getCode();
 $error['line'] = $e->getLine();
 $error['message'] = $e->getMessage();
 $error['trace'] = $e->getTrace();
 // Only send email reports on production server
 if(ENV('APP_ENV') == "production"){
 #1. Queue email for sending on "exceptions_emails" queue
 #2. Use the emails.exception_notif view shown below
 #3. Pass the error array to the view as variable $e
 Mail::queueOn('exception_emails', 'emails.exception_notif', ["e" => $error],
function ($m) {
 $m->subject("Laravel Error");
https://riptutorial.com/ 91
 $m->from(ENV("MAIL_FROM"), ENV("MAIL_NAME"));
 $m->to("webmaster@laravelapp.com", "Webmaster");
 });
 }
 }
 // Pass the error on to continue processing
 return parent::report($e);

The following is the view for the email or emails.exception_notif file.

$action = (\Route::getCurrentRoute()) ? \Route::getCurrentRoute()->getActionName() : "n/a";
$path = (\Route::getCurrentRoute()) ? \Route::getCurrentRoute()->getPath() : "n/a";
$user = (\Auth::check()) ? \Auth::user()->name : 'no login';
?>
There was an error in your Laravel App<br />
<hr />
<table border="1" width="100%">
 <tr><th >User:</th><td>{{ $user }}</td></tr>
 <tr><th >Message:</th><td>{{ $e['message'] }}</td></tr>
 <tr><th >Action:</th><td>{{ $action }}</td></tr>
 <tr><th >URI:</th><td>{{ $path }}</td></tr>
 <tr><th >Line:</th><td>{{ $e['line'] }}</td></tr>
 <tr><th >Code:</th><td>{{ $e['code'] }}</td></tr>
</table>

In the next lesson, we will study Events and Listeners in Laravel.

READ ALSO
Lesson 4 – Laravel Loops