DEV Community

Cover image for Exceptions Handling | PHP
Liutauras Kavaliauskas
Liutauras Kavaliauskas

Posted on

Exceptions Handling | PHP

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.

What are exceptions?

It's a state of code which require special treatment because it's not running as it's supposed to.

Types of exceptions

  • 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.

Good practices to use

  • 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 Exception class directly. Instead extend the Exception class 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.

Top comments (0)