简体   繁体   English

处理所有可能的(未经检查的)异常是否是好习惯?

[英]Is handling all possible (unchecked) Exceptions good practice?

Currently my signup looks like this: 目前,我的注册看起来像这样:

public void signup(User newUser) throws Exception {
    log.info("Sign up: " + newUser.getEmail());
    if (restService.emailAlreadyExists(newUser.getEmail())) {
        throw new Exception("Email already in use.");
    }
    List<Role> roles = new ArrayList<Role>();
    roles = roleRepository.findAllOrderedByName();
    roles.add(roleRepository.findByName("user"));
    newUser.setRoles(roles);
    newUser.setPassword(restService.getHashedValue(newUser.getPassword()));
    try {
        em.persist(newUser);
    } catch (Exception e) {
        throw new Exception("Just noobs use apps with less bugs. Try again. Now!");
    }
    log.info(newUser.toString());
    userEvent.fire(newUser);
}

In first order I'm just interested in two messages (will become FacesMessage ) for the user. 首先,我只是对用户的两条消息感兴趣(将变成FacesMessage )。 To prevent other cryptic messages for the user, I even would need to extend the try -block up to roles. 为了防止向用户提供其他隐秘消息,我什至需要将try -block扩展到角色。

Well, that would be bad practice, I guess. 好吧,我猜这是不好的做法。 Also using a generic Exception smells, they say. 他们说,还使用通用的Exception气味。 But: I detect following documented Exception s in this small piece of code: 但是:在这一小段代码中,我检测到以下记录的Exception

  • IllegalStateException
  • IllegalArgumentException
  • EntityExistsException
  • TransactionRequiredException
  • ObserverException

Even not speaking about the eight(!) Exception s of the method getSingleResult() of javax.persistence.TypedQuery . 甚至不说javax.persistence.TypedQuery方法getSingleResult()的八个(!) Exception

Should I really handle all Exception s in this example, or is it ok to skip a few (and/or maybe even use a generic Exception like above). 我应该在这个示例中真正处理所有Exception ,还是可以跳过一些Exception (和/或甚至可以使用上面的通用Exception )。

Best practice is: catch all exceptions separately and make as more custom log messages as possible. 最佳实践是:分别捕获所有异常,并制作尽可能多的自定义日志消息。 It's easier to understand faulty situations and to act accordingly. 了解故障情况并采取相应措施比较容易。

Reality in a typical business application is: try to group your exceptions (ex. group all possible exceptions caused by your method input, all the ones throwed by the db etc. etc.) and learn that sometimes you will put the infamous catch (Exception e) or rethrow a generic exception with a generic message... or people will start calling you about logs growing like elephants. 在典型的业务应用程序中,现实是:尝试将异常分组(例如,将由方法输入引起的所有可能异常,由数据库抛出的所有异常等分组),并了解有时您会放下臭名昭著的catch (Exception e)或使用一般性消息抛出一般性异常...否则人们会开始打电话给您关于象大象一样生长的原木的信息。

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

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