Exceptions

Igor Budasov
WebDevOps
Published in
1 min readMay 13, 2018
  1. If it’s a command, do not return a result, just throw an exception in case of fail (also related to CQRS cause you can not say if command succeed by returning value)
  2. An exception suppose to be custom and detailed, don’t use basic exceptions, it make it harder to debug
  3. Throw exception as fast as possible (kind of early return)
  4. Do not forget to catch the last most generic exception, if framework doesn’t handle it for you. Symfony does.
  5. Don’t rely on 3rd parties bundles’ exceptions. Catch all the 3rd exceptions and throw your own
  6. Child class shouldn’t throw new kinds of exceptions due to LSP
  7. Logic should not be hidden in catch construction. Use early return
  8. Put exceptions to the folder where they are used
  9. RuntimeException — can not be recovered during one response(failed connection, all what leads to 500),
    Exception — just a logical one, like entity not found or similar, all 4** codes
  10. Exceptions can be nested
  11. You can catch multiple exceptions at once

In data-layer, like service\provider

  1. You have to catch only specific exceptions — the ones you can process. Generic exceptions will be caught by framework without exposing any critical info outside.
  2. Make sure you propagate previous one (wrap one inside another, like a burrito)
  3. To understand it better — google “abstraction leaking”

In controllers

  1. Catch your own exception
  2. Throw new HTTP exception using framework’s exception
  3. It makes sense to propagate until controller level only exceptions which can be handeled. You can think of invalid input data (which must be handled before a controller, in the request obj)

--

--

Igor Budasov
WebDevOps

A traveller. A drinker. A photographer. A blogger. An engineer.