Custom fatal error handler in SLIM4

I am developing a REST API and want to support only JSON responses. I added a custom error handler this way:

$errorMiddleware = $app->addErrorMiddleware($config['error']['debug'], true, $config['error']['log']['communication']);
$errorMiddleware->setDefaultErrorHandler($container->get(ErrorHandler::class));

It works, but every now and then I got a fatal error, which is rendered by the default HTML renderer and I guess it is not logged as well. Is there a way to handle fatal errors with a custom error handler?

I know from my own frameworks, that this is a tricky question, because if the custom handler raises an error, then the code can collapse into an infinite error loop… But I still want to do this.

Hello sorry late answer I didn’t receive mailing notifications from here anymore

I have a start of an approach but I know it is far from perfect and is going to bully me again for pointing that old, dusty project of mine BUT I intend to release soon (as soon as I’m able… with low health it is gonna be quite challenging yay !) a new slim repository project on my GitHub ! With hopefully a better version of that and tools embedded focus on REST APIs development.

You can extend slim default ErrorHandler into more specialized Handlers
for instance:

and then register them for your app to use (as middlewares),
I personally used an intermediary middlewares.php file:

// Create Error Handler
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
$errorHandler->forceContentType('application/json');

// Create Shutdown Handler
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);

// Add Misc Middleware(s)
….

// Add Routing Middleware
$app->addRoutingMiddleware();

// Add Error Handling Middleware
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);

and then in index.php

// Register middleware
$middleware = require APP_ROOT . '/src/middlewares.php';
$middleware($app, $request);

From what I remember I mostly followed Slim 4 documentation..

(But I have to admit I may not be totally sharp or accurate on slim best practices, I’m still learning and didn’t practice for years now, plus the thing I didn’t push any project with slip in production… for now, but I will re-examine documentation and code snippets in the near future so I will probably update here and give you more feedback on all this :slight_smile: )

The sole time I tried slim was on the zelty php test years ago (I failed), but I loved slim really much (and yes @tj_gumis you were right that rushed 1 week code is quite ugly).

Cheers !

Hi!

Thanks, I’ll try it out. Happy Easter! :slight_smile:

1 Like