@ControllerAdvice甚至通过为RestControllers设置最高优先级而无法正常工作 [英] @ControllerAdvice even by setting the highest precedense for RestControllers not working as it should
问题描述
我正在使用SpringBoot 5.
我想捕获从RestController
引发的所有异常并显示自定义消息格式.
我已经简化了如下情况:
RestController
I am using SpringBoot 5.
I want to catch all exception thrown from RestController
and display customize message format.
I have simplified the situation like below:
The RestController
@RestController
@RequestMapping("/test")
public class TestRestController {
@Autowired
private TestService testService;
@GetMapping("/{id}")
public ResponseEntity<?> findById(@PathVariable int id) {
Test test = testService.find(id);
if(department!=null){
throw CustomException();
}
return new ResponseEntity<>(test, HttpStatus.OK);
}
}
ControllerAdvice异常处理程序:
The ControllerAdvice Exception handler:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);
@ExceptionHandler(value= {CustomException.class})
public ResponseEntity<ErrorDetail> handleCustomException(CustomException exception,
HttpServletRequest request) {
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.setTimeStamp(Instant.now().getEpochSecond());
errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
errorDetail.setTitle("Resource Not Found");
errorDetail.setDetail(exception.getMessage());
errorDetail.setDeveloperMessage(exception.getClass().getName());
return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
}
}
问题是RestExceptionHandler
无法正常工作,它没有捕获异常并返回修改后的错误消息格式.看来我的RestExceptionControllerClass
没有覆盖GlobalExceptionHandler
.我不知道为什么会这样,因为我已将RestExceptionHandler
标记为最高优先级.我将指导您调试该问题的所有指导.
The problem it is that RestExceptionHandler
is not working, it is not catching the exception and returning the modified error message format. It seem my RestExceptionControllerClass
is not overriding the GlobalExceptionHandler
. I don't know why this is happening because I have marked the RestExceptionHandler
with the highest precedense. I will appriciate any guidence to debug this problem.
推荐答案
问题是在我的CustomException
之前引发了另一个异常.在服务调用中,有一部分代码引发了我没想到的异常.所以我的RestExceptionHandler无法捕获异常,因为它没有处理该异常的方法,因此GlobalExceptionHandler
正在处理该异常.修复代码并确保抛出CustomExeption
后,一切正常进行. RestExceptionHandler
处理了异常并打印了自定义消息.
The problem was that another exception was thrown before my CustomException
. In the service call , there was part of code that threw an exception that i did not expect. So my RestExceptionHandler couldn't catch the exception because it didn't have a method to handle that exception and so the GlobalExceptionHandler
was handling that exception. After fixing the code and made sure that the CustomExeption
was thrown everything worked as it should. The RestExceptionHandler
handled exception and printed the custom message.
这篇关于@ControllerAdvice甚至通过为RestControllers设置最高优先级而无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!