Search code examples
laraveljwt

How to change the response messages in Tymon JWT package laravel


I want to change response messages in the Tymon JWT package. For example, while fetching the data with Invalid token I am getting this response

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

I need o change this from above response to below response

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

controller code

        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] );

            }

thank you in advance


Solution

  • You can customize the laravel Exceptions.

    inside app/Exceptions/Handler.php you can customize your message.

    
        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'
    
                    ];
    
                }
            }
    
        }