Middleware to transform exception type

I’d like to intercept exceptions and transform them from one class to another. The final class my original exception will be transformed to is perfectly handled by the default Slim exception handler, and I would like not to interfere with that. I’d also not to write my custom error handler because it will duplicate the logic that the default one already does.

Is there any way to create a middleware for exceptions?

You could implement a custom ErrorHandlerMiddleware that catches the exception and maps it to another exception and throws it at the end. Then let the slim error handler handle this exception.

Here’s what I got, works like a charm.

class ValidationErrorTransformer implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            return $handler->handle($request);
        } catch (ValidationError $e) {
            throw new ValidationException($request, $e->getMessage(), $e);
        }
    }
}

// ...

class ValidationException extends HttpBadRequestException
{
    public function __construct(ServerRequestInterface $request, ?string $title = '', ?Throwable $previous = null)
    {
        parent::__construct($request, null, $previous);
        $this->setTitle($title);
    }
}