samedi 30 juillet 2016

Catch exception from controller in middleware

I have a laravel controller that can throw an exception, and a global middleware that catches that exception. In semi pseudo code:

// App\Controllers\...
class Controller {
  function store() {
    throw new FormException; // via validation etc, but it's thrown here
  }
}

// App\Http\Middleware\...
class Middleware {
  function handle(Closure $next) {
    try {
      // Breakpoint 1
      return $next();
      // Breakpoint 2
    }
    catch (FormException $ex) {
      // Breakpoint 3
      exit('FormException caught!');
    }
  }
}

The problem is that the exception is never caught. Somwhere in the pipeline, the application catches the exception and prints a pretty error page, but it should be caught by my middleware so it can handle it properly.

  • Breakpoint 1 should trigger, and it does << good
  • Breakpoint 2 shouldn't trigger, and it doesn't << good
  • Breakpoint 3 should trigger, but it doesn't << what??

The only way I can imagine my middleware not catching it, is if it's caught somewhere deeper inside the pipeline, not further up/around, but I can't find any try/catch in other middleware, or in the pipeline execution code.

Where is this exception caught? Why?

This might not be a great pattern, but I don't care about that now. I'm more curious than anything else. Do I completely misunderstand Laravel's middleware?

Relevant Laravel code:

  • Kernel::handle() starts the middleware pipeline << this has a catch-all catch(), but my catch() comes first, right?
  • Pipeline::then() starts the middleware execution
  • Pipeline::getSlice() handles and creates the $next closures


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire