glance-project/error-middleware

Error middleware

v1.0.1 2024-08-05 13:11 UTC

This package is auto-updated.

Last update: 2024-12-05 13:48:42 UTC


README

A PSR-7 and PSR-15 compatible middleware for handling errors

Installation

Install with Composer

composer require glance-project/error-handler

Getting started

The error handler should be the first middleware executed by your application. In Slim, the last middlewared registed is executed first.

$app = \Slim\App::create();

$logger = /* ... */;
$errorMiddleware = ErrorMiddleware::create();
$errorMiddleware->setLogger($logger); // Optional. Accepts any PSR-3 logger
$errorMiddleware->debugMode(true);    // Optional. Set to false on production
$errorMiddleware->useSentry();        // Optional. Sentry must be installed and configured

$app->add(/* other middleware */);
$app->add($errorMiddleware);

/* Register routes here */

$app->run();

If the error handler is not the first registered middleware, exceptions on previous middleware will not be properly handled.

Exceptions

After initialized, all the uncaught exceptions are handled by this library.

The ErrorMiddleware behaves differently according to the type of the exception.

BaseException

Sometimes while developing an application, it is desired to abort everything and return an error to the user. This library provides a BaseException which encapsulates one or multiple errors.

An Error follows parts of the JSON API standard with the following optional fields:

  • Title
  • Detail
  • Code
  • HTTP status
  • Source
$errors = [
    new Error("Invalid email", "Email is bad formatted."),
    new Error(
        "Invalid password",
        "Password should contain at least 6 characters.",
        12345,
        400,
        new ErrorSource("user/password")
    ),
];

throw new BaseException(400, $errors);

The code above on your application would produce the following HTTP response:

STATUS: 400

{
    "status": 400,
    "errors": [
        {
            "title": "Invalid email",
            "details": "Email is bad formatted."
        }
        {
            "title": "Invalid password",
            "details": "Password should contain at least 6 characters.",
            "code": 12345,
            "status": 400,
            "source": { "pointer": "user/password" }
        }
    ]
}

You can also create your custom exceptions by extending the BaseException.

Other exceptions

Any other type of uncaught of exception will result on the following HTTP Response.

STATUS: 500

{
    "errors": [
        {
            "status": 500,
            "title": "Internal Error",
            "detail": "An unexpected server error occurred."
        }
    ]
}

If debugMode is on, additional debug information will be appended the the response body, such as file, line, message and trace.

Using Sentry

To send unknown errors to Sentry, install and initialize sentry/sdk. More information about setting up Sentry on PHP can be found at the official documentation.

composer require sentry/sdk
<?php

\Sentry\init([
    "dsn"         => getenv("SENTRY_DSN"),
    "environment" => getenv("ENVIRONMENT"),
]);

$app = \Slim\App::create();

$logger = /* ... */;

$errorMiddleware = ErrorMiddleware::create();
$errorMiddleware->useSentry();

$app->add(/* other middleware */);
$app->add($errorMiddleware);

// Register routes here...

$app->run();