We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Show 404 error page with micro app

I know of $di->notFound() and a solution based on middleware, but that is triggered only for non-matching URLs. But I want to do something like this:

class MyController {
    public function myAction() {
        $person = Persons::findFirst();
        if (!$person) {
            throw new NotFoundException();
        }
    }
}

For this, I've created a custom error handler. What I not want to do is redirecting to a special /404 page. I want to render a custom error page for 404 errors (raised by NotFoundMiddleware and NotFoundException) and 500 errors (raised by any exception) without redirecting user. As micro app is lacking a dispatcher (so ->forward() is not useable), is there any clean way to solve this?



79.0k
Accepted
answer

In micro, w/o dispatcher you can't do much, but to revert to native PHP side of things OR do the following:

@mohahn remember my ErrorHandler from previous post?

/**
 * Not found handler
 */
$app->notFound(function () { ErrorHandler::stopMiddleware(404, 'RESOURCE_NOT_FOUND : The server has not found anything matching the Request-URI.', 255); });

that will trigger ErrorHandler with 404 status, defined message and code (exception thrown) so the user will get HTTP 404.



4.2k

@stamster Yes, I've seen your solution. Based on another post in this forum, I've created my own error handler, which can detect and handle 404 errors by error code raised by custom exceptions.