【问题标题】:how log and rethrow the entire class如何记录和重新抛出整个班级
【发布时间】:2020-02-06 10:50:47
【问题描述】:

我正在使用弹簧。

我有一个包含多种方法的类。在每种方法中我都必须写:

public void method1(){
    try{
       //anything
    }
    catch(Exception e){
       Log.error(e);
       throw e;
    }
}
public void method2(){
    try{
       //anything
    }
    catch(Exception e){
       Log.error(e);
       throw e;
    }
}
public void method3(){
    try{
       //anything
    }
    catch(Exception e){
       Log.error(e);
       throw e;
    }
}
public void method4(){
    try{
       //anything
    }
    catch(Exception e){
       Log.error(e);
       throw e;
    }
}

我可以写一些不必在每个方法中都写的东西吗?也许是注释?

【问题讨论】:

  • 在 spring 中检查 @ControllerAdvice 注释。链接:spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
  • 您预计会出现什么样的异常?如果我发现有人在代码审查期间发现了普通的异常,我通常会拒绝它。如果你不处理,你为什么要抓住它们?
  • 我必须在此处记录每个异常。如果我们对我为什么在这里这样做进行抽象,是否有一种解决方案可以不在所有方法中重复这种尝试和捕获?
  • 那么为什么不简单地在调用方法上捕获它们呢?

标签: java spring exception


【解决方案1】:

由于您使用的是 Spring,@ControllerAdvice 对于这种情况来说将是一个不错的脆性解决方案。

你所要做的就是做一些配置并像这样定义你的全局异常处理类

@ControllerAdvice
public class ExceptionControllerAdvice {

    // Handles Custom exceptions. MyException in this case
    @ExceptionHandler(MyException.class)
    public ModelAndView handleMyException(MyException mex) {     
        ModelAndView model = new ModelAndView();
        ...
        return model;
    }

    // Handles all the exceptions
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {     
        ModelAndView model = new ModelAndView();
        model.addObject("errMsg", "This is a 'Exception.class' message.");
        ...
        return model;     
    }
}

请参阅this 帖子,了解在 Spring 中配置不同类型的错误处理技术。

【讨论】:

    【解决方案2】:

    如果只需要重新抛出异常,有两种解决方案:

    import lombok.SneakyThrows;
    @SneakyThrows //annotation on method of lombok library
    
    import static org.apache.commons.lang3.exception.ExceptionUtils.rethrow;
    rethrow() //method from Apache commons library
    

    1)

    @SneakyThrows(Exception.class) //without specifying will rethrow all exceptions
    public void method1(){
           //anything
    }
    

    2)

    public void method1(){
        try{
           //anything
        }
        catch(Exception e){
           Log.error(e);
           rethrow(e);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2012-02-21
      • 2015-11-18
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多