gpt4 book ai didi

java - 如何使用ControllerAdvice中的ExceptionHandler处理从 Controller 中的ExceptionHandler抛出的异常?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:52:03 25 4
gpt4 key购买 nike

我有自定义异常扩展异常(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 adviceMyException2 and MyException3 are working as intended but MyException1 fails with 
"Failed to invoke @ExceptionHandler method .....handleMyException1"

最佳答案

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

Option(1):从 Controller 中删除 @ExceptionHandler(MyException1.class) 方法,以便 MyGlobalExceptionHandler 自动处理它。

Option(2) :创建 MyException4(它是 MyException1 的包装器,添加了信息)并从 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),这是手动调用 MyGlobalExceptionHandlerhandleAllException() 因为它不是一个好习惯。相反,您应该简单地抛出异常,@ExceptionHandler 将自动处理。

手动调用的另一个问题是,在将来的某个时间点,由于您的一些流程手动调用 MyGlobalExceptionHandler 而一些流程由框架。

关于java - 如何使用ControllerAdvice中的ExceptionHandler处理从 Controller 中的ExceptionHandler抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com