zeuxisoo / php-slim-whoops

PHP whoops error on slim framework
132 stars 10 forks source link

Rethrowing exceptions #28

Closed killua-eu closed 2 years ago

killua-eu commented 4 years ago

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 commented 4 years ago

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