Slim 4 - How to handle multiple errors

Hi there

I have an application which runs on Slim3 in production. Currently I’m working on upgrading to Slim4.
I use an Error Handler and a Shutdown Handler as described in the Slim User Guide: https://www.slimframework.com/docs/v4/objects/application.html#advanced-custom-error-handler

The only difference is, that I use Twig and therefore I return a Twig-rendered HTML-String from the HttpErrorHandler. This works just fine.
The Problem is, when I have for example a 404 the HttpErrorHandler outputs the correct Twig-rendered Error-Page to the browser. If additionally there is a PHP Error in the code, the ShutdownHandler is triggered, which invokes the HttpErrorHandler and then this outputs an additional Twig-rendered Error-Page to the browser.
The second Error-Page is displayed under the first one in the browser.

At the moment I’m searching for ideas how to output only one error-page. Is it possible to detect the last error? Or can I suppress the output until the last error?

Thanks a lot for your support!

philipp

Hi @philipp

The shown ShutdownHandler uses its own (a second) ResponseEmitter, although there must be only one per request.

// this will output the second page
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);

I suggest using a ErrorHandlerMiddleware instead to catch and handle all PHP errors, warnings, and notices. Here is the code: Catching PHP warnings, notices and errors

Hi Daniel

Thanks a lot for your support! I really appreciate that.
I implemented the ErrorHandlerMiddleware, like you suggested and it works like a charm.
In the beginning I struggled a bit, because the errors were not logged. The problem was, that my test-code, which produced the php-warning was in my app.php. When I put the code in a controller, the warning was logged like expected.

The ErrorHandlerMiddleware is now combined with a custom ErrorHandler. So in case of php warnings and notices I get a log entry and a mail from monolog. If there’s an error, the ErrorHandler shows either a Twig 404 or a Twig Error page and logs the error.

Nomäl viele Dank und än Gruäss us Frauefäld

1 Like