How do you set up custom error pages in Slim Framework?

How do you set up custom error pages in Slim Framework?

To set up custom error pages in Slim Framework, follow these minimal steps:

Steps to Set Up Custom Error Pages in Slim Framework:

  1. Define Custom Error Handlers: You can create custom error handlers for different types of errors (e.g., 404, 500). Slim provides an easy way to configure custom handlers via the error middleware.

 

Example

<?php
use Slim\Factory\AppFactory;

$app = AppFactory::create();

// Define a custom 404 handler
$app->getContainer()->set('notFoundHandler', function () {
    return function ($request, $response) {
        $response->getBody()->write("Oops! Page not found.");
        return $response->withStatus(404);
    };
});

// Define a custom error handler for internal server errors (500)
$app->getContainer()->set('errorHandler', function () {
    return function ($request, $response, $exception) {
        $response->getBody()->write("An internal error occurred: " . $exception->getMessage());
        return $response->withStatus(500);
    };
});
?>
  1. Custom Error Pages for Specific Status Codes:
You can also define custom error pages for specific HTTP status codes. For instance, a 404 page for “not found” errors or a 500 page for internal server errors.

Example

<?php
$app->getContainer()->set('notFoundHandler', function () {
    return function ($request, $response) {
        $response->getBody()->write("This page does not exist. Please check the URL.");
        return $response->withStatus(404);
    };
});

$app->getContainer()->set('errorHandler', function () {
    return function ($request, $response, $exception) {
        $response->getBody()->write("Oops! Something went wrong: " . $exception->getMessage());
        return $response->withStatus(500);
    };
});
?>
  1. Running the Application:
After setting up custom error pages, run the application as usual.

Example

<?php
$app->run();
?>

Optional: Use HTML Templates for Custom Error Pages

You can also render an HTML template for error pages instead of just writing plain text. For example, using a Twig or PHP view renderer:

Example

<?php
$app->getContainer()->set('errorHandler', function () {
    return function ($request, $response, $exception) {
        $renderer = new \Slim\Views\Twig('path/to/templates', ['cache' => false]);
        return $renderer->render($response, 'error.twig', ['error' => $exception->getMessage()])
                        ->withStatus(500);
    };
});
?>

Related Questions & Topics