By default, TokenMismatchException produces a user-hostile 500 internal server error. I'm trying to handle it in a more friendly way.
The problem is that I cannot pass an error message back to the user once the session has timed out.
In app/Exceptions/Handler.php, I check for the TokenMismatchException and try to redirect the user back with a message:
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException)
{
return redirect()->back()->with( 'csrf_error', 'Sorry, your session timed out. Please try again.' );
}
return parent::render($request, $e);
}
Now, a token mismatch can occur for two reasons: the token is wrong/missing, or expired. If I delete the token field and submit the form, everything works as expected: the user is redirected back and shown the error message.
But if I let the session expire (by setting the session lifetime to 0.1), then it doesn't work. The user is redirected back, but there is no error message.
I think this may be happening because the session has not yet been recreated, so the message has nowhere to be stored?