Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JustinLien's avatar

How to Throw TokenMismatchException

Hi,

I've wrote a custom error handling for TokenMismatchException in app\Exceptions\Handler.php.

How do I correctly throw an exception to see my custom message?

throw new TokenMismatchException;

Does not seem to do the trick.

0 likes
5 replies
anon12822's avatar

Whoops, I read the post wrong!

Try this:

 public function render($request, Exception $e)
    {
        if ($e instanceof \Illuminate\Session\TokenMismatchException) {
            dd('blah');
        }

        return parent::render($request, $e);
    }
anon12822's avatar

@JustinLien It's thrown automatically on post forms if the tokens don't match up.

If you want to test it, just append a string on to the end of a CSRF token on the form.

Kryptonit3's avatar
Level 11

@JustinLien

// MyController.php
use Illuminate\Session\TokenMismatchException;

class MyController extends Controller {

    public function mismatch()
    {
        throw new TokenMismatchException;
    }

}
// routes.php
get('mismatch', ['uses' => 'MyController@mismatch']);

go to mysite.com/mismatch

or just put the following in your routes.php file and go to mysite.com/mismatch

use Illuminate\Session\TokenMismatchException;
get('mismatch', function(){
    throw new TokenMismatchException;
});
1 like
JustinLien's avatar

@krballard94 no problem.

I see what I was doing wrong. I am seeing the TokenMismatchException in routes.php line error, but no message. My thrown exception is correct.

The issue was my custom message. I was doing something like this:

// does not work
if ($e instanceof \Illuminate\Session\TokenMismatchException) {

    return 'my custom error message';

}

Where it should have been something like this:

// working example
if ($e instanceof \Illuminate\Session\TokenMismatchException) {

    return response('my custom error message');

}

Please or to participate in this conversation.