spring boot 全局异常处理可以通过配置 @controlleradvice 配合 @exceptionhandler 来捕获反射调用异常。具体做法是定义一个全局异常处理器类,在其中添加针对 java.lang.reflect.invocationtargetexception 的异常处理方法,该方法可以提取原始异常并返回统一的错误响应。这样做能确保在通过反射调用方法时发生的任何异常都能被统一拦截和处理。

如何配置全局异常处理器以捕获 InvocationTargetException?
要捕获反射调用异常,需要创建一个继承自 ResponseEntityExceptionHandler 或仅使用 @RestControllerAdvice 注解的类。在该类中,编写一个方法并使用 @ExceptionHandler(InvocationTargetException.class) 注解。当反射调用抛出异常时,Spring MVC 会自动将该异常传递给此方法。你可以在方法参数中获取异常对象,并通过 getTargetException() 方法获取底层抛出的真实异常,从而进行更细致的错误分类或日志记录。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import java.lang.reflect.InvocationTargetException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvocationTargetException.class)
public ResponseEntity<String> handleInvocationTargetException(InvocationTargetException ex) {
Throwable target = ex.getTargetException();
return ResponseEntity.status(500).body("Reflection failed: " + target.getMessage());
}
}
反射调用中的嵌套异常如何处理和展示?
反射调用异常通常包裹着目标方法实际抛出的异常。在处理 InvocationTargetException 时,应优先检查其内部的 targetException。如果目标方法抛出的是运行时异常(如 NullPointerException),可以直接将其作为业务逻辑错误处理;如果是受检异常,则可能需要转换为运行时异常或特定的业务异常。通过在异常处理器中判断 targetException.getClass(),可以实现对不同底层异常的差异化响应。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import java.lang.reflect.InvocationTargetException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvocationTargetException.class)
public ResponseEntity<Object> handleNestedException(InvocationTargetException ex) {
Throwable target = ex.getTargetException();
if (target instanceof IllegalArgumentException) {
return ResponseEntity.badRequest().body("Invalid argument passed to method");
} else if (target instanceof NullPointerException) {
return ResponseEntity.status(400).body("Null reference in method call");
}
return ResponseEntity.status(500).body("Unknown reflection error: " + target.getMessage());
}
}
当反射调用的目标方法抛出自定义业务异常时会发生什么?
如果反射调用的目标方法抛出自定义的業務異常(例如 BusinessException),该异常会被包装在 InvocationTargetException 中。在全局异常处理器中,你需要显式地解包这个异常。如果希望直接返回业务异常中的状态码和消息,可以在 handleInvocationTargetException 方法中检查 targetException 是否为你定义的业务异常类型,如果是,则直接提取其信息并构建响应。这样可以保持业务异常语义的一致性,避免将业务逻辑错误掩盖在通用的反射异常之下。


















