I am working on a PHP framework and am currently designing error handling. Based on what I have read on SO, I should only use exceptions for, well, exceptional situations. Therefore throwing an exception when an incorrect password is entered is wrong.
Should I avoid using exceptions when I want to return a server error code to the user (eg. 404 Page Not Found)? If so, should I write my own error handling class?
Your code shouldn't throw an exception to interact with the user, it should throw the exception to notify a higher level of code that something unrecoverable happened.
Now, depending on what happened, you may want to respond with a certain HTTP status code. But at that point you're not throwing exceptions to trigger a server error, you're catching exceptions and giving the user an appropriate response.
If the questions is what should happen when an article/blog/item/etc is requested that doesn't exist -- well, if it's possible for the code responsible for displaying the information to just set the response code, then by all means, don't use exceptions.
If you're using a MVC framework, and your individual controllers can set the response code, then let them.
And if the topmost exception handler can use a http response code to better present the error message to the user, then let it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With