抛出异常以返回服务器错误是不好的,例如。 404页面未找到? [英] Is it bad to throw exceptions to return server errors, eg. 404 Page Not Found?

查看:142
本文介绍了抛出异常以返回服务器错误是不好的,例如。 404页面未找到?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发PHP框架,目前正在设计错误处理。基于我在SO上阅读的内容,我只应该使用异常,以及异常情况。因此,当输入错误的密码时会抛出异常。



如果我想向用户返回服务器错误代码,我应避免使用异常(例如404页未找到)?如果是这样,我应该写我自己的错误处理类吗?

解决方案

你的代码不应该抛出异常与用户交互,它应该抛出异常来通知一个不可恢复的代码的更高级别的代码。



现在,根据发生的情况,您可能需要使用某个HTTP状态代码进行响应。但是,在这一点上,你不会抛出例外情况来触发服务器错误,您将捕获异常并给予用户适当的响应。



如果问题是要求不存在的文章/博客/项目/ etc应该发生什么,那么如果负责显示信息的代码可能只是设置响应代码,那么一切手段,不要使用异常。



如果您使用MVC框架,并且您的个人控制器可以设置响应代码,那么让它们。



如果最上面的异常处理程序可以使用http响应代码来更好地向用户显示错误消息,那么请放。


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.

这篇关于抛出异常以返回服务器错误是不好的,例如。 404页面未找到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆