Skip to main content
7 of 7
Update class names and links from D8.3.x to D8.8.x
4uk4
  • 101.7k
  • 7
  • 173
  • 217

Exception handling in Drupal

Exceptions are handled by FinalExceptionSubscriber, unless there is a more specific exception subscriber handling it before.

Core defines several of them, which are listed here: 27 uses of GetResponseForExceptionEvent


How default exceptions are handled

When you throw an exception in code

throw new \exception('ID ' . $id . ' not found in table xyz!');

the default exception handler returns a 500 http status code with this standard message:

The website encountered an unexpected error. Please try again later.

If you enable error reporting (admin/config/development/logging) you get a more verbose exception message displayed on screen:

The website encountered an unexpected error. Please try again later.

Exception: ID abc not found in table xyz! in Drupal\mymodule... (line 123 of modules/custom/mymodule/src/....php).


Conclusion

Now, what you want to do depends on how much information you want to disclose to the public. Often if you don't find the data you are looking for a 404 exception is more meaningful than a 500 exception. If none of the core exception handling fits your purpose you can implement a custom exception subscriber:

Handle database connection exception via custom handler

4uk4
  • 101.7k
  • 7
  • 173
  • 217