Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to throw exceptions to return server errors, eg. 404 Page Not Found?

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?

like image 411
Peter Horne Avatar asked May 07 '10 17:05

Peter Horne


1 Answers

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.

like image 158
Tim Lytle Avatar answered Oct 19 '22 23:10

Tim Lytle