如何解决@ControllerAdvice 方法没有被执行,它执行基本响应类
我使用 productDetail 方法和 handleMethodArgumentNotValid 方法编写了我的 Spring Boot ProductController 类。 handleMethodArgumentNotValid 方法用@ExceptionHandler(MethodArgumentNotValid.class) 注释。它工作得很好。之后我删除了 Controller 类中的 handleMethodArgumentNotValid 方法,因为我想使用 @ControllerAdvice。但它正在执行项目的 BaseException 类。它没有执行@ControllerAdvice 方法。
Here is my Controller class.
@PostMapping("/productDetail")
public void productDetail(@Valid @RequestBody ProductDetail productDetail) {
System.out.println("I am in Controller ProductDetail ....");
try {
iOrderService.updateProductDetail(productDetail);
} catch (Exception e) {
//Executes Base Exception class @R_501_4045@ion here
...
}
}
Here is my ControllerAdvice .
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,HttpHeaders headers,HttpStatus status,WebRequest request
) {
same code that I had in handleMethodArgumentNotValid method of ProductController class here
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.UNPROCESSABLE_ENTITY.value(),"Validation error. Check 'errors' field for details."
);
for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
errorResponse.addValidationError(fieldError.getField(),fieldError.getDefaultMessage());
}
return ResponseEntity.unprocessableEntity().body(errorResponse);
}
如何处理 MethodArgumentNotValidException 使其不执行 BaseException 类?
解决方法
您的全局异常处理程序只能处理未捕获的异常。因此,如果您希望它处理 iOrderService.updateProductDetail(productDetail);
抛出的任何内容,则需要删除 try/catch。
我怀疑您对 productDetail()
的测试输入实际上并未导致 MethodArgumentNotValidException
。或者您的全局异常处理程序不包含在您的组件扫描中。出于测试目的,我建议向全局异常处理程序添加一个“catchAll”方法。只是想看看它是否捕获了任何异常。
@ExceptionHandler(Exception.class)
protected ResponseEntity<ExceptionEnvelope> catchAll(Exception exception,WebRequest request) {
return buildResponse(HttpStatus.INTERNAL_SERVER_ERROR,exception,request);
}
在那里设置一个断点,看看你是否能够命中它。我以前遇到过这样的问题,结果是我的假设是错误的,关于 spring 在不同情况下会抛出哪些异常。像这样捕获所有异常将允许您验证 GlobalExceptionHandler 是否正确连接,并且还会告诉您实际抛出的是哪个异常。
,我将控制器类中的 RestController 注释更改为 @Controller 注释,并使用 @ResponseBody 注释方法,并且它起作用了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。