# Error handling

HttpSoft\ErrorHandler\ErrorHandlerMiddleware from the HttpSoft\ErrorHandler package is responsible for error handling. It is recommended that this middleware be registered first in the pipeline so that if an error occurs in the next middleware, the error handler can catch it.

/**
 * @var HttpSoft\Basis\Application $app
 */

$app->pipe(HttpSoft\ErrorHandler\ErrorHandlerMiddleware::class);
// Other middleware.
$app->pipe(ErrorOccurredMiddleware::class);
// Other middleware.

App\Infrastructure\Http\ErrorHandlerMiddlewareFactory has been added for the convenience of creating a middleware instance.

# Response generators

HttpSoft\ErrorHandler\ErrorHandlerMiddleware accepts an instance of the HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface in its constructor, which will generate a response with information about the error.

Available response generators:

To use a different response generator, you need to change the App\Infrastructure\Http\ErrorHandlerMiddlewareFactory.

$errorHandler = new ErrorHandlerMiddleware(new ErrorJsonResponseGenerator($container->get('config')['debug']));
// Change to:
$errorHandler = new ErrorHandlerMiddleware(new WhoopsErrorResponseGenerator());

To use your own response generator, you need to create a class that implements the HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface and pass its object to the constructor when creating the HttpSoft\ErrorHandler\ErrorHandlerMiddleware.

# Error listeners

Error listeners are added by the error handler using the HttpSoft\ErrorHandler\ErrorHandlerMiddleware::addListener() method and are triggered only when an error occurs.

Available error listeners:

You can add as many custom error listeners as you want. To do this, create a class that implements the HttpSoft\ErrorHandler\ErrorListenerInterface and add its object to the error handler.

# Additional functionality

Two request handlers are available that return a 404 Not Found response:

These handlers are used by the application instance if no matches were found with the current route.

Several HTTP exceptions have been created for convenience.

Feel free to throw these exceptions in your code. The error handler will catch them and insert the status code, and the error reason phrase in the generated response. If an exception is thrown with a code that is not a valid HTTP response status code (for example: new throw \RuntimeException();), a response with the status 500 Internal Server Error is generated.