Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rethrowing exceptions #28

Closed
killua-eu opened this issue Dec 23, 2019 · 1 comment
Closed

Rethrowing exceptions #28

killua-eu opened this issue Dec 23, 2019 · 1 comment

Comments

@killua-eu
Copy link

killua-eu commented Dec 23, 2019

On some routes, I rethrow exceptions to achieve a better user experience. When using the standard Slim 4 error middleware, the thrown ErrorException will by default generate a 500 response. When the ErrorException gets re-thrown as a HttpNotFoundException, I get a 404 error (expected behaviour). When I use php-slim-whoops, I get 500 on ErrorException (expected) but also a 500 when rethrown as HttpNotFoundException (should be 404). Am I doing something wrong or is this a bug? Example code below.

Throw an ErrorException

class Auth {
    // ...
    public function getUser($uid) { 
        if (!(v::intVal()->positive()->validate($uid))) {
            throw new ErrorException('Validation failed (positive integer required).', 550);
        }
        // ...
   }

Rethrow it

use App\Classes\Auth\Auth;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpBadRequestException;
use Slim\Exception\HttpNotFoundException;
use Throwable;

class Accounts extends AbstractTwigController
{
 
    public function read(Request $request, Response $response, array $args = []): Response
    {
        $auth = new Auth($this->db);
        try {
            $users = $auth->getUser($request, $args['uid']);
        } catch (Throwable $e) {
            if ($e->getCode() == 550) { 
               throw new HttpNotFoundException($request, 'User not found');
            } else {
               throw new HttpBadRequestException($request, 'Something went wrong.');
            }
@zeuxisoo
Copy link
Owner

In slim 4, the default error middleware will handle each exception in the related exception handler. These exception handlers were pre-defined in the slim. like:

https://github.com/slimphp/Slim/blob/2c6d2be6ae09f48c76a9b29baa1226c4152f1a8e/Slim/Middleware/RoutingMiddleware.php#L83-L100

But, In the whoops error handler, All exception will handle by one exception handler. this exception handler cannot identify which case should be handled.

Back to your case, I think you should need to create a custom handler for whoops. also, the whoops handler should be used in development mode maybe better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants