[英]NoSuchElementException @ExceptionHandler in SpringBoot not working
我在 SpringBoot 中创建了一个自定义异常处理程序
@RestControllerAdvice
public class DataApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoSuchElementException.class)
public final void **handleNoSuchElementException**(NoSuchElementException ex) {
System.err.println("This is throwing :"+ex.getMessage());
}
...
@ExceptionHandler({ Exception.class })
public ResponseEntity<Object> **handleAll**(final Exception ex) {
...
并抛出异常
throw new NoSuchElementException("SomelogicalDescription");
但是每次我抛出这个 NoSuchElementException 时,都会执行 handleAll 而不是 handleNoSuchElementException。
我可能会遗漏一些非常微不足道的东西。 帮我找出来。
***To change NoSuchElementException with NotFoundException does not make any difference.***
看起来您@RestControllerAdvice
活动。
注意:如果配置了适当的 HandlerMapping-HandlerAdapter 对(例如 RequestMappingHandlerMapping-RequestMappingHandlerAdapter 对,这是 MVC Java 配置和 MVC 命名空间中的默认值),则会处理 @RestControllerAdvice。 休息控制器建议
改用@ControllerAdvice
。 控制器建议
你有一个void
处理程序 - 那么你为什么期待回应?
你在那里返回什么? 应该是这样的:
@ControllerAdvice
public class InvalidValuesExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ InvalidValuesException.class })
protected ResponseEntity<Object> handleInvalidRequest(RuntimeException exc, WebRequest request) {
InvalidValuesException ive = (InvalidValuesException) exc;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
BasicResultMessage msg = new BasicResultMessage(ive.getDataId(),
ive.getMessage());
SendDataResult result = new SendDataResult(false, msg);
return handleExceptionInternal(exc, result, headers, HttpStatus.BAD_REQUEST, request);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.