klein / klein.php

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

Setting response code to 404 results in 200. #266

Open sweiguny opened 9 years ago

sweiguny commented 9 years ago

Hi, when I get an error, i will come into the onError callback.

Here i want to set the response-codes dependent to the exceptions that were caught. e.g. 404 if a PageNotFoundException was caught.

but even, when i do $router->response()->code(404); i get a 200 response instead of 404. what am I doing wrong? i definitely come into the block where i echo "here".

$this->klein->onError(function($router, $errorMsg, $exceptionName, $exception) {

            if ($exception instanceof PageNotFoundException) {
                $router->response()->code(404);
                echo "here";
            } else if ($exception instanceof PermissionDeniedException) {
                $router->response()->code(403);
            } else if ($exception instanceof NotYetImplementedException) {
                $router->response()->code(501);
            } else {
                $router->response()->code(500);
            }
        });

thanks in advance

Rican7 commented 9 years ago

Hmm, strange. Are you making sure to actually send the response after setting the code? The onError() handlers are called when a "stop the world" exception is caught, so you might have to send the response yourself.

sweiguny commented 9 years ago

Okay, i added $router->response()->send(); at the end of onError and it's behaving as expected. Thanks.

But i think, this is not really documented anywhere :)

despite i didn't call send() before, i got an output... so klein must send the request somehow else?

Rican7 commented 9 years ago

Yea, Klein should be sending the response no matter what, but its hard to tell with just your snippet. If you're rethrowing the exception anywhere or somehow skipping the rest of the dispatch process, it would cause an issue and not send the response.

I'd love to document Klein further. There's already a decent amount documented, but yea I'd love to have more of its implicit behaviors documented. All in due time.