Not Found Handler without Error Middleware?

In Slim3 I was able to disable the default Error Handler but still use the default Not Found Handler (404). I think this is not possible in Slim4, as the Error Middleware must be added to Slim in order to set the Not Found Handler.

As I would still like to use my custom error handler with Slim 4, how would you recommend I go about handling 404s? I think some options are:

  • use .htaccess in Apache
  • create a Slim catch all else route which returns custom 404 response
  • somehow register my custom error handler as the Slim Error Middleware

In Slim 4 the ErrorMiddleware is still optional to add a custom 404 Not found handler.
You can add a custom NotFoundErrorMiddleware with a try/catch block, that catches the Slim HttpNotFoundException in the catch block and let the ErrorMiddleware handle all other uncatched errors.
It is also possible to remove the ErrorMiddleware completely, and handle everything yourself.

1 Like

Thanks for the response. I do want to remove the ErrorMiddleware completely. Actually, I’m not adding it in the first place. Are you saying it’s possible to do that and use Slim’s Not Found Handler? The Upgrade Guide shows the Not Found Handler being added to the ErrorMiddleware.

$errorMiddleware = $app->addErrorMiddleware(true, true, true);

// Set the Not Found Handler
    function (ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails) {
        $response = new Response();
        $response->getBody()->write('404 NOT FOUND');
        return $response->withStatus(404);

Yes, this is actually the “recommend” way to handle the Not Found error.

I’m confused, as it seems to require ErrorMiddleware.

If you add the ErrorMiddleware then you can add custom handlers (functions or invokable classes) to the Error Middleware using the setErrorHandler method. This is the recommended way.

If you don’t want to add the ErrorMiddleware, then you need to add a custom ErrorMiddleware to the stack, that catches and handles the specific exceptions, e.g. the HttpNotFoundException etc.

The 3. option is a combination of both, one or more custom ErrorMiddlewares + the Slim ErrorMiddleware as “fallback” for all other errors.

1 Like

Thanks a lot for the explanation. I’ve managed to get a custom 404 working from .htaccess. There’s a small problem I may ignore. Plus, there are benefits of handling from Slim like writing request info to a db events table. So, I may play around with setting my error handler as Slim’s ErrorMiddleware.