klein/klein.php

Calling abort() from onError() throws an HttpException

Opened this issue · 2 comments

I couldn't quite figure out if this is desired behaviour, but it seems kind of counter-intuitive (it seems to make sense to abort the request if an error is encountered), so I'm cautiously opening an issue about this...

Code (2.1):

$router = new \Klein\Klein();

$router->respond('*', function () {
  throw new ErrorException('Just testing...');
});

$router->onHttpError(function ($code) {
  if($code == 500) {
    echo 'Oh no, an exception! Server error!';
  } else {
    echo '404 Not found.';
  }
});

$router->onError(function ($router) {
  $router->abort(500);
});

$router->dispatch();

Result: Fatal error: Uncaught exception 'Klein\Exceptions\HttpException'

Possible related to #286?

jk3us commented

From what I can tell, onError($callback) just builds a list of things that get called if you call $klein->error(), and it doesn't actually have anything to do with handling exceptions.

I think the proper thing to do would just be to call $klein->abort() instead of throwing that exception.

I also think the documentation regarding errors, exceptions, and staus codes could be a lot better...

Ah, that clears things up. I think it would still be very useful to have Exceptions handled by a method (if not onError()) as they are caught by Klein and wrapped in an HttpException anyway. The HttpException is quite cumbersome for handling errors (as the "original" exception is buried deep inside).