Lesson 4
Error Handling in Laravel Applications
Error Handling in Laravel Application

Welcome to this new lesson on Error Handling in your Laravel ToDo application! As you continue to transform your app into an enterprise-friendly application, a good understanding of error handling is crucial. In our earlier lessons, we touched upon integrating your database and configuring middleware. Now, we’ll focus on ensuring your application gracefully handles errors and provides helpful feedback when things go awry.

What You'll Learn

During this lesson, you'll learn how to customize error handling using Laravel’s exception handler. This involves setting up error views, like a custom 404 page, to provide users with clear information and a smooth experience even when errors occur. To remind you, error handling is not a new concept; it's similar to setting up middleware in that both enhance app reliability.

Ever visited a website and encountered a 404 error when you tried to access a page that doesn't exist? Now, let's imagine you're the developer of that website and you want a custom 404 page to guide users back to the main application. This is where error handling comes in. By customizing error messages, you can provide users with a clear path back to the main application, ensuring they don't get lost or frustrated.

Let's see an example of custom error page in Laravel:

php
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Page Not Found</title> 5</head> 6<body> 7 <h1>404 - Page Not Found</h1> 8 <p>Sorry, the page you are looking for could not be found.</p> 9 <a href="{{ url('/todos') }}">Back to ToDo List</a> 10</body> 11</html>

Here, we've created a custom 404 page that displays a message and a link to the main application.

Now, let's see how we can integrate this custom error page into our Laravel application. To do that, we need to modify the app/Exceptions/Handler.php file which contains the exception handler for our application.

php
1<?php 2 3namespace App\Exceptions; 4 5use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; 6use Illuminate\Database\Eloquent\ModelNotFoundException; 7use Throwable; 8 9class Handler extends ExceptionHandler 10{ 11 protected $dontReport = []; 12 13 protected $dontFlash = [ 14 'current_password', 15 'password', 16 'password_confirmation', 17 ]; 18 19 public function register() 20 { 21 $this->renderable(function (ModelNotFoundException $e, $request) { 22 return response()->view('errors.404', [], 404); 23 }); 24 } 25}

Let's break down the code snippet above:

  • We've created a custom 404 page in the resources/views/errors directory named 404.blade.php.
  • In the handler we have a class Handler that extends ExceptionHandler.
  • The dontReport property contains an array of exceptions that should not be reported. We've left it empty for now.
  • The dontFlash property contains an array of inputs that should not be flashed to the session - in this case the password fields.
  • The register method is used to register custom exception handling logic. Here, we're using the renderable method to handle the ModelNotFoundException exception. When this exception is thrown, the custom 404 view is returned with a 404 status code.
    • The response()->view() method is used to return a view response with the custom 404 view and a 404 status code.

Note, that by default Laravel will show the content of the resources/views/errors/404.blade.php file when a 404 error occurs, even if you don't have a custom exception handler defined in the Handler class.

There is a nuance in Laravel error handling that you should be aware of. If the custom error file name is different from 404.blade.php, you need to update the render method in the Handler class to handle the custom error file. For example, if you have a custom error file named custom-404.blade.php, you would update the render method instead of the register method:

php
1use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 2 3... 4 5public function render($request, Throwable $exception) 6{ 7 if ($exception instanceof NotFoundHttpException) { 8 return response()->view('errors.custom-404', [], 404); 9 } 10 11 return parent::render($request, $exception); 12}

In this code snippet, we're checking if the exception is an instance of NotFoundHttpException. If it is, we return the custom 404 view with a 404 status code. Otherwise, we call the parent render method to handle the exception.

With this, when a 404 error occurs, the custom 404 view will be displayed to the user with whatever message you've defined in the view file.

Why It Matters

Proper error handling enhances your application's professionalism and user experience. Just imagine walking into a mall and getting lost without signs or directions; it's frustrating. Similarly, users navigating your app without proper error messages can quickly become disheartened. Mastering error handling means your application can anticipate, adapt, and communicate issues clearly, making it reliable and user-friendly. As you venture into the next practices, remember, handling errors effectively shows professionalism and care for the user, traits valued in any enterprise-level application.

Now that you're ready, let's dive deeper into the practice section and hone your skills in error handling!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.