JWT 异常处理

2020-09-24  本文已影响0人  谢高升

原文地址 https://www.xiegaosheng.com/post/view?id=125

jwt  json web token 默认token失效等会抛出 错误对接口很不友好,

下面是laravel,thinkphp框架异常处理


//laravel 

App\Exceptions\Handler

//tp的话需要在app目录下面的provider.php文件中绑定异常处理类,例如:

    // 绑定自定义异常处理handle类

    'think\exception\Handle'       => '\\app\\exception\\Http',

    自定义类需要继承think\exception\Handle并且实现render方法

代码如下


public function render($request, Exception $exception)

{

    //判断jwt错误异常

    if ($exception instanceof TokenExpiredException){

        return response()->json(['code'=>1050,'msg'=>$exception->getMessage()], $exception->getStatusCode());

    }

    if ($exception instanceof TokenInvalidException){

        return response()->json(['code'=>1050,'msg'=>$exception->getMessage()], $exception->getStatusCode());

    }

    if ($exception instanceof JWTException){

        return response()->json(['code'=>1050,'msg'=>$exception->getMessage()], $exception->getStatusCode());

    }

    if ($exception instanceof UnauthorizedHttpException){

        return response()->json(['code'=>1050,'msg'=>$exception->getMessage()], $exception->getStatusCode());

    }

    return parent::render($request, $exception);

}

上一篇 下一篇

猜你喜欢

热点阅读