如何在ControllerAdvice中使用ExceptionHandler处理控制器中ExceptionHandler抛出的异常?

时间:2016-11-08 11:11:30

标签: java spring spring-mvc exception-handling spring-aop

我有自定义异常扩展异常(MyException1,MyException2,MyException3)

@Controller
public class MyController {
    /*
       Method throwing MyException1
       Method throwing MyException2
       Method throwing MyException3
    */

    @ExceptionHandler(MyException1.class)
    public void handleMyException1(Exception ex){
        //Do something
        throw ex;
    }
    @ExceptionHandler(MyException2.class)
    public void handleMyException2(Exception ex){
        System.out.println("Exception Logged inside Controller")
    }
}

@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public void handleAllException(Exception ex){
        System.out.println("Exception logged Outside Controller");
    }
}
My Intention: To log MyException1 from controller advice
              To log MyException2 inside handler in controller itself
              To log MyException3 from controller advice
MyException2 and MyException3 are working as intended but MyException1 fails with 
"Failed to invoke @ExceptionHandler method .....handleMyException1"

1 个答案:

答案 0 :(得分:1)

您可以为异常处理选择以下选项之一:

选项(1):从控制器中删除@ExceptionHandler(MyException1.class)方法,以便MyGlobalExceptionHandler自动处理它。

选项(2):创建MyException4MyException1的包装,附加信息)&从Controller中抛出它,如下所示:

@Controller
public class MyController {
    /*
       Method throwing MyException1
       Method throwing MyException2
       Method throwing MyException3
    */

    @ExceptionHandler(MyException1.class)
    public void handleMyException1(Exception ex){
         //MyException4 exe4 = new MyException4();
        // Add the required details to it
        throw exe4;
    }

    @ExceptionHandler(MyException2.class)
    public void handleMyException2(Exception ex){
        System.out.println("Exception Logged inside Controller")
    }
}

@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public void handleAllException(Exception ex){
        System.out.println("Exception logged Outside Controller");
    }
}

P.S。:我没有在这里添加Option(3),这是手动调用MyGlobalExceptionHandler的{​​{1}},因为这不是一个好习惯。相反,您应该简单地抛出异常,handleAllException()将自动处理。

手动调用的另一个问题是,在将来的某个时间点,调试异常将会出现问题,因为您的某些流程会手动调用@ExceptionHandler,并且某些流程会被框架调用。 / p>