我正在使用 Spring 。
我有一个具有多种方法的类。在每个方法中我必须写:
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;
}
}
引用this在 Spring 中配置不同类型的错误处理技术的帖子。
关于java - 如何记录并重新抛出整个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60093246/