In a module within a drupal hook I'd like to conditionally trigger a 403 for the user.

I could archieve this e. g. by throwing an exception

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

But is this the right way to do it? I know that a redirect in general should not be done directly from a hook, in order to not break the chain of hooks to be executed, instead I should use a middleware like described e.g. in this answer

Is this relevant here, too? Do I have to write a middleware or stuff instead of throwing the exception within a hook, or does the exception not exit Symfony/Drupal within the hook, but "end" the process in a correct way?

I've seen the solution in combination with exit(), too

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

but I think this would do exactly what I try to not do regarding the hook chain?

Thank you in advance!

1 Answer 1


Throwing the exception is the correct way for your code to stop building a 200 response and instead return a 403 response. Don't use exit(). The AccessDeniedHttpException is a specific exception class handled by a kernel exception subscriber returning the themed 403 page, which can be configured in admin UI.

If it's possible to determine the 403 situation in advance, then add an access callback to the route. Then you don't need to throw the exception later, because it is already checked in the routing process and this makes it possible to hide the link if the current user has no access to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.