Have you ever had experience with unfriendly error message when something goes bad? Or just
500 status page?
Some user do. You get notified about that as a developer. However the user cannot tell exactly what went wrong. Here goes checking logs and so on.
To keep user experience in high standarts one should never get in such situation. Here comes exceptions handling.
It's a state of code which require special treatment because it's not running as it's supposed to.
- Logic exceptions - requires a fix or a change in the code or any content managed by the developer. Such exception is mainly an interal check or a kind of assertion.
- Runtime exceptions - may be caused by the input from the user, or an error in communication with other services. Such exceptions shouldn't require a fix in the code.
- Don't use a boolean as an exception replacement. You should throw exceptions for error handler instead. You shouldn't force others to actively check the return value of the function to see if everything went alright.
- Don't throw the
Exceptionclass directly. Instead extend the
Exceptionclass or use one of the available sub-classes. Throwing generic class is preventing catching a specific problem.
- Do not hide what is going wrong by catching all exceptions. Your could should fail loudly with a big error message instead. If you're logging all the issues it might take some time for someone to notice that. For example if your dabatase cannot be accessed there's nothing you can do to fix this.
- Provide a meaningful message in the exception.
- Don't show exception to the user. User won't probably understand it. You're revealing project structure. The handler should return more general and user friendly message instead.