Better handling of tokenmismatchexception in Laravel


At my day job, we recently enabled monitoring of our web server logs for 500 level error codes. Subsequent to this, we discovered that we started getting an influx of these errors from our Laravel sites.

This seemed strange, so I dug further to find that due to the layered manner in which middleware is processed, TokenMismatchExceptions were being generated for routes that probably shouldn’t have.

The problem

In digging further into this issue, it became clear that as Laravel processes middleware before handling any route logic — and because Laravel 5.1 has CSRF protection applied globally by default — a route that either did not support POST requests or simply did not exist would generate a TokenMismatchException erroneously.

Further to that, because we were not explicitly catching the exception, it was being rendered with the standard ‘Whoops’ message via the default exception handler.


Originally published at