Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Slim Framework Exception Handling

I just finished creating an API application with slim framework, initially, in my code I use a dependency container to handle all exceptions thrown, the code is below.

//Add container to handle all exceptions/errors, fail safe and return json
$container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use ($container) {
        //Format of exception to return
        $data = [
            'message' => $exception->getMessage()
        ];
        return $container->get('response')->withStatus(500)
            ->withHeader('Content-Type', 'application/json')
            ->write(json_encode($data));
    };
};

But instead of throwing a 500 Server Error all the time I would like to add other HTTPS reponse code. I wonder if I could get help on how to go about that.

public static function decodeToken($token)
{
    $token = trim($token);
    //Check to ensure token is not empty or invalid
    if ($token === '' || $token === null || empty($token)) {
        throw new JWTException('Invalid Token');
    }
    //Remove Bearer if present
    $token = trim(str_replace('Bearer ', '', $token));

    //Decode token
    $token = JWT::decode($token, getenv('SECRET_KEY'), array('HS256'));

    //Ensure JIT is present
    if ($token->jit == null || $token->jit == "") {
        throw new JWTException('Invalid Token');
    }

    //Ensure User Id is present
    if ($token->data->uid == null || $token->data->uid == "") {
        throw new JWTException("Invalid Token");
    }
    return $token;
}

The problem is even more from functions like the above one, since slim framework decides to handle all exceptions implicitly, I have no access to use try catch to catch any errors

like image 812
James Okpe George Avatar asked Jan 16 '16 13:01

James Okpe George


2 Answers

Not that hard, it is simple. Rewrite the code:

container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use ($container) {
        //Format of exception to return
        $data = [
            'message' => $exception->getMessage()
        ];
        return $container->get('response')->withStatus($response->getStatus())
            ->withHeader('Content-Type', 'application/json')
            ->write(json_encode($data));
    };
}

So what does this code do? You basically pass a $response as before, and what this code does is that it gets the status code from the $response object and passes it to the withStatus() method.

Slim Documentation for referring to status.

like image 115
Hassan Althaf Avatar answered Oct 18 '22 20:10

Hassan Althaf


You could use the withJson() method of Slim\Http\Response Object

class CustomExceptionHandler
{

    public function __invoke(Request $request, Response $response, Exception $exception)
    {
        $errors['errors'] = $exception->getMessage();
        $errors['responseCode'] = 500;

        return $response
            ->withStatus(500)
            ->withJson($errors);
    }
}

and if you are using dependency injection you could do

$container = $app->getContainer();

//error handler
$container['errorHandler'] = function (Container $c) {
  return new CustomExceptionHandler();
};
like image 2
Mushtaq Jameel Avatar answered Oct 18 '22 22:10

Mushtaq Jameel