2

I'm sending my requests to the server using ajax and somehow at times, I may get TokenMismatchException on the server. Now, I want to handle this both on the backend as well as frontend. For this, I used a reference from this StackOverflow link:

public function render($request , Exception $exception)
{
    //TODO Check the following if() block code validity for production server
    if ($exception instanceof \Illuminate\Session\TokenMismatchException){
        if ($request->expectsJson() ){
            return Response::json([
                'message'      => 'Token mismatch (CSRF token mismatched)' ,
                'message-type' => 'danger' ,
                'new_csrf_token' => csrf_token()
            ], $exception->getStatusCode());
        }
        return redirect()
            ->back()
            ->exceptInput('password')
            ->with([
                'message'      => 'Validation Token was expired. Please try again' ,
                'message-type' => 'danger' ,
            ]);
    }

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

Using this JSON response, I want to display a prompt message on the front end as well as update the CSRF token to resend the request.

But I get an error saying:

Call to undefined method Illuminate\Session\TokenMismatchException::getStatusCode()

Any ideas how can I manage to handle this exception for ajax request?

Community
  • 1
  • 1
Birendra Gurung
  • 2,168
  • 2
  • 16
  • 29

2 Answers2

2

Laravel token miss match exception code is 419, you can use directly 419 instead of $exception->getStatusCode()

webdevtr
  • 480
  • 2
  • 6
  • Code 419 doesn't correspond to any status as stated in this link: http://www.restapitutorial.com/httpstatuscodes.html . Will it be good to use this status code ? – Birendra Gurung Jun 12 '18 at 07:14
  • Yes but laravel use this code, `elseif ($e instanceof TokenMismatchException) { $e = new HttpException(419, $e->getMessage(), $e); }` Please check `vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php` line 203 – webdevtr Jun 12 '18 at 07:19
1

TokenMismatchException is a Non-Http exception and so it won't return a status code of it. You can just redirect to the desired view or the login page as per the requirement.

Nitish Patra
  • 289
  • 5
  • 20