5

I have a service provider that does stuff(for lack of a better word).

Several functions in that service provider deal with a custom table in the database. Lets assume that in a function an id is passed, if said id doesn't exist I want to stop the process. Throwing out an exception would normally be the way to go, because this is an exceptional situation. The process cannot continue without that information.

I'm not exactly sure how to handle that in Drupal. I don't have that much experience with it.

I noticed that Symfony has an exception handler itself but I'm sure Drupal handles things differently.

Do I log the exception and kill the process? Just throw it out and hope for the best?

1 Answer 1

11

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

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.