Home > database >  Laravel 8 bearer token exception handling if bearer token not found
Laravel 8 bearer token exception handling if bearer token not found

Time:02-22

Hello I can't understand how to set error message when user put some wrong bearer token currently I am not getting any exceptional error message if I try wrong bearer token in postman.

        try{
            return $token = $request->bearerToken();
        }catch(Exception $e){
            return $e->message();
        }
        

CodePudding user response:

in app/Exceptions/Handler.php add this function and change the message as you want

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'haha'], 401);
    }

    return redirect()->guest('login');
}

here return haha message

note define this before write the function
Illuminate\Auth\AuthenticationException;

  • Related