What do we need the PHP-exception code for? Any use case scenario?
Okay, its a very lame question for many but I hope I will have overwhelming response :)
When I throw an Exception in PHP I can add a code to the message.
I catch an exception and handle it according to its type (Like InvalidArgumentException
or OutOfBoundException
). I log the message or display it or do whatever is suitable.
I can add also append a previous exception to trace a path to the origin of the error.
BUT one thing I have never used or never thought of: how useful is code?
For example:
throw new Exception("db Error", $code, $previousException);
What do I do with $code
?
The message is for display to the user, while the code is for use by your program. So for example, in your "database error" example, you might make up a set of codes like
- Can't connect
- Error during query
- Empty result
- Error closing connection
and then use the appropriate code. Then when other parts of your code saw they exception, they would know what happened and could possibly deal with it intelligently.
How $code
is interpreted is dependent on the exception type. For example, if you have an Exception
subclass that represents a MySQL database error, then the $code
could be the native MySQL error code. In the case of a low-level IO error, this could be a value from <errno.h>
.
Basically, $code
should contain whatever you need to programmatically handle an exception. Most exceptions are meant to be handled somewhere. If all of your exceptions are simply displayed as errors, then $code
is only useful if you need to include an error code from a library like the MySQL client library.
I've seen implementations (CakePHP) where the $code
is used as HTTP status code.
I've implemented that concept with a subset of exceptions. So all exceptions extending from HttpException
which are thrown respond with HTTP errors
In object oriented languages, the type of the exception conveys what type of error it is. However, if for example you have two things that can generate the same exception type, the error code could be used to give more detail.
The error code is a widely used feature in non-object oriented language to convey what type of error it is.
I personally use the code to get a compressed error message, that user can send to the support. For example, let's say the user tries to authenticate, and he fails, my code throws an AuthenticateException
with the message: Failed to authenticate
, and a specific code referring to the real issue behind the failure. The user will only see the authentication message, and the code, thus not knowing what the real reason of the failed authentication was. He is then advised, that if needed, contact the support team with the code.
Based on the exception code, our support colleagues can easily pin-point what was the real reason for the failed authentication (invalid password, inexistent user-name, account was suspended, etc.) and may help the user accordingly.