glance-project/error-handler

This package is abandoned and no longer maintained. The author suggests using the glance-project/error-middleware package instead.

Error middleware

v0.2.0 2021-09-21 19:00 UTC

This package is auto-updated.

Last update: 2022-02-18 16:58:14 UTC


README

Error%20Handler.png?theme=light&pattern=architect&style=style_1&md=1&showWatermark=0&fontSize=100px&images=exclamation&widths=auto 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();