PHP: Slim Framework Exception Handling -
i finished creating api application slim framework, initially, in code use dependency container handle exceptions thrown, code below.
//add container handle exceptions/errors, fail safe , return json $container['errorhandler'] = function ($container) { return function ($request, $response, $exception) use ($container) { //format of exception return $data = [ 'message' => $exception->getmessage() ]; return $container->get('response')->withstatus(500) ->withheader('content-type', 'application/json') ->write(json_encode($data)); }; };
but instead of throwing 500 server error
time add other https reponse code. wonder if on how go that.
public static function decodetoken($token) { $token = trim($token); //check ensure token 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 present if ($token->jit == null || $token->jit == "") { throw new jwtexception('invalid token'); } //ensure user id present if ($token->data->uid == null || $token->data->uid == "") { throw new jwtexception("invalid token"); } return $token; }
the problem more functions above one, since slim framework decides handle exceptions implicitly, have no access use try catch
catch errors
not hard, simple. rewrite code:
container['errorhandler'] = function ($container) { return function ($request, $response, $exception) use ($container) { //format of exception return $data = [ 'message' => $exception->getmessage() ]; return $container->get('response')->withstatus($response->getstatus()) ->withheader('content-type', 'application/json') ->write(json_encode($data)); }; }
so code do? pass $response
before, , code gets status code $response
object , passes withstatus()
method.
Comments
Post a Comment