Search code examples
silexabort

silex abort() on BootableProviderInterface ignores provided code, response has 200 always


I have a silex BootableProvider to check for some requirements on every request before executing calls to any of my end points. All works good, except that when I use the $app->abort('403', 'forbidden for some reason'); anywhere in the boot() method, the response always returns code 200. The 'forbidden' message is correctly displayed and execution is interrupted as expected fortunately, but not having a meaningful Status code on the response makes it hard/cumbersome to process these failure responses.

I'm using silex 2.0.4.

If i however, execute the $app->abort(...) from any of my endpoints which implement ControllerProviderInterface, in the same request thread, the responses have the correct response codes I specify in the abort, so I'm thinking it's a timing issue.

Any advise is greatly appreciated.

Sample Code:

class BootProvider implements BootableProviderInterface {


    function boot(Application $app) {
        $app->abort(403, 'not allowed');
    }

}

...

$app->register(new My\Api\BootProvider());

I've tried passing headers to override the Status to no avail.

Thanks!


Solution

  • In you case you should get just exception Fatal error: Uncaught exception.... Service providers are booted before kernel handle cycle, so errors are not processed.

    Try to add event listener or middleware that will be executed before controllers and will make all checks.

    $app->before(function (Request $request, Application $app) {
        $app->abort(403, 'not allowed');
    });
    

    http://silex.sensiolabs.org/doc/2.0/middlewares.html