klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

Handling 404's : What if I want to serve a full 404 document instead of a few lines of text. #358

Open thinsoldier opened 7 years ago

thinsoldier commented 7 years ago

https://github.com/klein/klein.php/wiki/Handling-404's

The suggested technique in the wiki only shows how to send a few lines of text when 404 errors happen. I can't figure out how to server a fully styled document for 404. I mean I can serve a full document but then the http header changes from 404 to 200.

$klein->onHttpError(function ($code, $router) {
    switch ($code) {
        case 404:
             // This works but causes the http header to be 200 instead of 404
             $router->service()->render('app/views/404.php');

             //$router->response()->body('404 Not Found');

            break;
        case 405:
            $router->response()->body(
                'You can\'t do that!'
            );
            break;
        default:
            $router->response()->body(
                'Oh no, a bad error happened that caused a '. $code
            );
    }
});
Spirit55555 commented 7 years ago

I use this:

$klein->onHttpError(function ($code, $router) {
    if ($code == 404) {
        $service = $router->service();
        $service->render('views/404.php');
    }
});

It returns a 404 response header.

thinsoldier commented 7 years ago

@Spirit55555 I changed my code to exactly match yours and it definitely is still giving me 200 OK.

To get 404 I had to force headers to be sent.

$klein->onHttpError(function ($code, $router) {
    if ($code == 404) {
        $router->response()->sendHeaders( true, true);
        $service = $router->service();
        $service->render('views/404.php');
    }
});
Spirit55555 commented 7 years ago

That is strange, it works without forcing the headers here.

lucaslm commented 5 years ago

As far as I can tell, this issue appeared for me after updating php version. Then I had to force the headers as well.