Exceptions
Published in
1 min readMay 13, 2018
- 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)
- An exception suppose to be custom and detailed, don’t use basic exceptions, it make it harder to debug
- Throw exception as fast as possible (kind of early return)
- Do not forget to catch the last most generic exception, if framework doesn’t handle it for you. Symfony does.
- Don’t rely on 3rd parties bundles’ exceptions. Catch all the 3rd exceptions and throw your own
- Child class shouldn’t throw new kinds of exceptions due to LSP
- Logic should not be hidden in catch construction. Use early return
- Put exceptions to the folder where they are used
- 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 - Exceptions can be nested
- You can catch multiple exceptions at once
In data-layer, like service\provider
- 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.
- Make sure you propagate previous one (wrap one inside another, like a burrito)
- To understand it better — google “abstraction leaking”
In controllers
- Catch your own exception
- Throw new HTTP exception using framework’s exception
- 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)