Displaying an Error Page

Learn how to display an error page to the users when something goes wrong.

Creating an error script

Let’s improve the exception handler by showing the error page. First, create a new page script, pages/error.php. Paste the following code in it:

Press + to interact
<?php
$title = 'Error';
include(__DIR__ . '/../_header.php');
?>
<h1>An error occurred</h1>
<?php
include(__DIR__ . '/../_footer.php');

We don’t need to add a URL for it to the $urlMap because the error page isn’t a normal page. We will only show it when we catch an exception. To do this, we have to modify the call to set_exception_handler() in bootstrap.php:

Press + to interact
<?php
set_exception_handler(
function (Throwable $exception) {
include(__DIR__ . '/pages/error.php');
}
);
session_start();

Go to http://APPLINK/oops, and see the error page that it now shows:

For regular users, this is good, but for developers, this isn’t great. For us, it is important to know what exactly went wrong.

Note: You don’t have to go anywhere and open any URL as we have set things up for you on our platform. We have used http://APPLINK just as a placeholder. The URL to view the application is different on our platform. ... ...

Access this course and 1400+ top-rated courses and projects.