Catch exception from controller in middleware
I had the same problem. When reading the thread Rudie mentioned, they give a possible solution there which worked for me:
public function handle(Request $request, Closure $next) {
$response = $next($request);
// 'Catch' our FormValidationException and redirect back.
if (!empty($response->exception) && $response->exception instanceof FormValidationException) {
return redirect()->back()->withErrors($response->exception->form->getErrors())->withInput();
}
return $response;
}
Apparently this is by design:
Yes, this is the beavhiour starting from L5.2. Throwing an exception causes the response to be set as that returned from the exception handler, and then the middleware is allowed to backout from that point.
I think that's very strange. Pluggable middleware would be perfect for catching exceptions.
Two ways to still do this:
- Proper: in
App\Exceptions\Handler
, which is not good enough, because a package can't touch that Funky: take the original exception object from the response object:
$response = $next($request); $exception = $response->exception;