如何更改Tymon JWT包laravel中的响应消息

时间:2019-12-02 06:41:15

标签: laravel jwt

我想更改Tymon JWT软件包中的响应消息。例如,在使用无效令牌获取数据时,我会收到此响应

 "message": "Invalid token.",
"exception": "Tymon\\JWTAuth\\Exceptions\\TokenInvalidException",

我需要将其从上方回复更改为下方回复

 "errors": "Invalid token.",
"exception": "Tymon\\JWTAuth\\Exceptions\\TokenInvalidException",

控制器代码

        try {
             $assign = AssignmentResource::collection(DB::table('assignments')->whereIn('assignments.academic_id',$ids)
            ->whereIn('assignments.batch',$batch)
            ->whereIn('assignments.course',$classid)->get());

            } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

                return response()->json(['success' => false,'errors' => $e,'status' => 404] );



            } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

                return response()->json(['success' => false,'errors' =>$e,'status' => 404] ); 

            } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

                return response()->json(['success' => false,'errors' =>$e,'status' => 404] );

            }

提前谢谢

2 个答案:

答案 0 :(得分:1)

如果您看到Tymon JWT Auth的Exception Handling页,那么它即将推出:

一种实现此目标的方法就像使用try..catch

  try {

    // Your code here.

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

    // return your response.

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

     // return your response.

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

     // return your response.

    }

答案 1 :(得分:1)

您可以自定义laravel异常。

app/Exceptions/Handler.php内,您可以自定义消息。


    public function render($request, Exception $exception)
    {
        if ($request->is('api/*') || $request->expectsJson() || $request->is('webhook/*')) {
            if ($exception instanceof Tymon\JWTAuth\Exceptions\TokenInvalidExceptio) {

                return [
                    'errors' => $exception->getMessage(),
                    'exception' => 'your message'

                ];

            }
        }

    }