如何处理Java Web应用程序中的异常?
我想以警告用户发生的错误的方式处理异常。
我所知道的是:
servlet.java
private void registerUser(...){
...
try{
DAOUser daoUser = new DAOUser();
daoUser.insert(user);
catch(HibernateException he){
...
}
DAOUser.java
public void insert(User user) throws HibernateException {
...
}
这是最好的方法吗?如果没有,你会建议什么?
此致, 瓦尔特·恩里克.
i would like to handle my exceptions in a way to warning the user about the errors that occured .
What i know is something like:
servlet.java
private void registerUser(...){
...
try{
DAOUser daoUser = new DAOUser();
daoUser.insert(user);
catch(HibernateException he){
...
}
DAOUser.java
public void insert(User user) throws HibernateException {
...
}
This is the best approach ? If not, what would you suggest ?
Best regards,
Valter Henrique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
异常可以通过不同的方式处理。在这种情况下,异常似乎会导致用户通知或错误消息。
现在,您显示的示例不应抛出任何此类异常,您需要通知用户。首先,验证用户输入;其次,不要使用异常来实现程序的流程。
好吧,也有例外,我们需要用一些消息通知用户。这可以在控制器中完成,通常使用存储在属性文件中的消息。
您必须知道在哪里捕获异常、在哪里抛出异常以及在哪里记录异常。 这里我想建议的第一件事是不要同时进行,即抛出和记录。如果您认为记录是合适的,请不要抛出它。如果您认为抛出是合适的,那么就不要记录它。当您按照这种方式进行操作时,您将自动知道需要记录哪一个以及要抛出哪一个。这并不意味着某些异常会在不记录的情况下消失。该方法不会进一步抛出该异常,而是负责记录该异常。
另一件事是知道在哪里使用
checked
异常以及在哪里使用runtime
。抛出运行时异常的方法本身更容易使用。但这并不意味着您应该始终使用运行时异常。我希望你能明白我的观点。
An exception can be handled in different ways. In this case, it seems that the exception is resulting in a user notification or an error message.
Now, the example you have shown should not throw any exception of that sort, where you need to notify user. First, validate user input; second, don't make the flow of your program using exceptions.
Well, there are exceptions where we need to notify the user with some message. That can be done in
controller
, typically, using messages stored in property files.You must know where to catch exception, where to throw it, and where to log. Here first thing I would like to suggest is not to do both, throw and log. If you think logging is appropriate, don't throw it. If you think throwing is appropriate, then don't log it. When you follow this way, you will automatically know which one you need to log and which one to throw. That doesn't mean some exceptions would go away without logging. The method, which doesn't throw that further, holds the responsibility to log that exception.
Another thing is to know where to use
checked
exception and where to useruntime
. The methods which throw runtime exceptions are somewhat easier to use, per se. But that doesn't essentially mean that you should always use runtime exceptions.I hope you are getting my points.
更好的方法是
我们的 servlet wiki 页面很好地演示了错误消息内容
Well the better way would be
Our servlet wiki page demonstrated error message stuff nicely