开发者

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 incor开发者_Python百科rect 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.


Exceptions are not control flow mechanisms.


Exceptions should be limited to ONLY those times that the app truly can't handle the situation.

As you said, throwing an exception for an incorrect password is very wrong.

The only server error type situations I can come up with are if a required resource (like your sql server) wasn't available.

Beyond that, access denied, etc are all common occurrences that your application should have a normal way to handle.


I think you are talking about two different things:

  1. Errors that occurs when something has gone wrong in the framework itself, or the framework is used in a way that it should not work.
  2. HTTP status codes (404 Page Not Found mentioned in the topic is status code).

In the first situations throwing exception is the right way to do, if you want to solve the problem by using object orientated approach. HTTP status codes are part of the HTTP protocol and your framework should not handle them in any way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜