Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling exceptions within controller methods #77

Open
mazuhl opened this issue Mar 13, 2018 · 1 comment
Open

Handling exceptions within controller methods #77

mazuhl opened this issue Mar 13, 2018 · 1 comment

Comments

@mazuhl
Copy link

mazuhl commented Mar 13, 2018

Is it possible to throw an exception in a controller method and catch that in the dispatcher/router? Controller methods are called in the Dispatcher using call_user_func_array, which doesn't allow for catching exceptions.

If not, how else would you return early from a method?

class MyController {

    public function anyIndex() {
        $this->checkAccess('edit');
    }

    private function checkAccess($permission) {
        if ($userPermission != $permission) throw new Exception("You don't have permission", 401);
    }
}
@akrz
Copy link

akrz commented Mar 16, 2018

You are probably using a closure on a filter. If you declare the filter as

$app->router->filter('auth', [MyController::class, 'checkAccess']);

And in the class:

class MyController
{
    public function checkAccess()
    {
        if ($userPermission != $permission) throw new Exception("You don't have permission", 401);
    }
}

It'll catch it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants