# Invoke 404 Not Found Handler

**URL:** <https://discourse.slimframework.com/t/invoke-404-not-found-handler/3712>\
**Category:** Questions\
**Created:** [December 9, 2019, 4:34pm UTC](https://discourse.slimframework.com/t/invoke-404-not-found-handler/3712 "2019-12-09T16:34:02Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [December 11, 2019, 8:12pm UTC](https://discourse.slimframework.com/t/invoke-404-not-found-handler/3712/3 "2019-12-11T20:12:07Z")

</div>

You will only get a fatal error if you don’t register the Slim ErrorMiddleware:

```php
$app->addErrorMiddleware(true, true, true);

```

You could also define a custom error handler for the `\Slim\Exception\HttpNotFoundException::class`.

Example:

```php
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, $logErrors, $logErrorDetails);

$errorMiddleware->setErrorHandler(\Slim\Exception\HttpNotFoundException::class, function (
    \Psr\Http\Message\ServerRequestInterface $request,
    \Throwable $exception,
    bool $displayErrorDetails,
    bool $logErrors,
    bool $logErrorDetails
) {
    $response = new \Slim\Psr7\Response();
    $response->getBody()->write('My custom 404 error');

    return $response->withStatus(404);
});

```

You custom error handler could also be a class with a `__invoke()` method.

To trigger the 404 error handler just throw a HttpNotFoundException.

```php
throw new \Slim\Exception\HttpNotFoundException($request);

```

Or you just register a custom default error handler to handle the HttpNotFoundException.

```auto
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);

```

[http://www.slimframework.com/docs/v4/middleware/error-handling.html](http://www.slimframework.com/docs/v4/middleware/error-handling.html)

---

_[View the full topic](https://discourse.slimframework.com/t/invoke-404-not-found-handler/3712)._
