0

My database credentials are right, and everything works. But sometimes the mysql server is down, and I would like to display a custom error message to my api consumers/users, if that happens, and I get Doctrine\DBAL\Exception\ConnectionException.

Unfortunately the database connection is lazy loaded, so the connection is not establised until the first $em->flush() call. It is obviously not possible to wrap every service which contains $em->flush() in a try catch block.

How is it possible to handle these kind of database errors?

Iter Ator
  • 8,226
  • 20
  • 73
  • 164

3 Answers3

1

Without much information only a vague answer can be proposed, so here is my try:

I suppose you use one or more controllers or other concept of entry points for user requests. This is where I'd ultimately see error handling: In the code layer that is at the edge of the application and the "gateway" to the user. If it's a single controller, you can obviously add try/catch around calls to your business logic. If it's multiple controllers, you will need to add the try/catch to all of them which could be quite cumbersome, so maybe it makes sense to have one piece of code where all requests pass. A benefit of this approach is that this is not limited to Doctrine but maybe you also might want to handle other errors in such a way.

If you use the Symfony framework, such an exception handler is quite easy, as they do exactly this: Use common infrastructure code (named HttpKernel) where all requests are handled, and have an exception handling mechanism for all exceptions that bubble up to this infrastructure code. If you don't want to use Symfony, a look at the source code (https://github.com/symfony/symfony) or the docs (https://symfony.com/doc/current/index.html) might still be useful for inspiration.

If you catch only specific exception types or everything (\Exception or even \Throwable) is of course up to you. I personally would like to avoid having library dependencies bleed too much into my code base so would wrap them in custom exceptions.

umulmrum
  • 153
  • 1
  • 8
0

If you use some kind of framework, then it probably defines an error handler. You should consider extending this error handler to handle your errors and show a fancy page to your user.

If you're not using any framework, checkout how to do it in PHP here: https://www.php.net/manual/fr/function.set-error-handler.php

Obviously, you may have some cases having the database is critical, you will need to take each case one by one: no magic solution here, sorry.

Nek
  • 2,715
  • 1
  • 20
  • 34
-1

Take a look for a another question can be the solution for your question

Catch db error with Doctrine\DBAL\Exception

  • That question/answer does not solve the issue. The questioner simply wraps an insert operation in a try-catch block – Iter Ator Jan 30 '21 at 20:52