如何记录和重新抛出整个类



我正在使用弹簧。

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

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将是一个很好的脆皮解决方案。

您所要做的就是做一些配置并定义全局异常处理类,如下所示

@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;     
}
}

请参阅这篇文章,了解如何在 Spring 中配置不同类型的错误处理技术。

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

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);
}
}

最新更新