简体   繁体   English

如何处理Java Web应用程序中的异常?

[英]How to handle exceptions in Java Web Applications?

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. 此致,Valter Henrique。

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 kind where you need to notify user. 现在,您显示的示例不应抛出需要通知用户的任何异常。 First of all, validate user input and don't make the flow of your program using exception. 首先,验证用户输入,不要使用异常使程序流程。

Well, there are exceptions where we need to notify user with some message. 好吧,我们需要通过一些消息通知用户。 That can be done in controller using messages stored in property files, typically. 这通常可以在控制器中使用存储在属性文件中的消息来完成。

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. 如果您认为投掷是合适的,那么请不要记录它。 If 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. 不进一步抛出的方法,有责任记录它。

Another thing is to know where to use checked exception and where to use runtime. 另一件事是知道在哪里使用已检查的异常以及在何处使用运行时。 The methods which throw runtime exceptions are somewhat easier to use, per say. 根据说,抛出运行时异常的方法更容易使用。 But that doesn't essentially mean that you should always use runtime exceptions. 但这并不意味着您应该始终使用运行时异常。 Well, that also depends. 嗯,这也取决于。

I hope you are getting my point. 我希望你明白我的观点。

Well the better way would be 那么更好的方法是

  • First Isolate Service/DAO/Controller/View layers. 首先隔离服务/ DAO /控制器/视图层。
  • Throw exception from service , handle it in controller and act it accordingly. 从服务中抛出异常,在控制器中处理它并相应地执行它。

Our servlet wiki page demonstrated error message stuff nicely 我们的servlet wiki页面很好地展示了错误消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM