java - SpringBoot 中的 NoSuchElementException @ExceptionHandler 不起作用
问题描述
我在 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 对,例如 MVC Java 配置和 MVC 命名空间中默认的 RequestMappingHandlerMapping-RequestMappingHandlerAdapter 对,则处理 @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);
}
}
推荐阅读
- python-3.x - 在Python中的二进制搜索算法中查找数组的中间索引值
- reflection - Python 3.7:检测从类中访问的属性名称
- excel - 在 Excel 中的 2 个值之间以设定的间隔减去
- linux - 获取未安装 /proc 的执行路径
- python - 使用 python 的请求库无法登录网站
- c# - 计算 LookAt 而不应用它
- python - 使用 savedmodel simple_save 和 tensorflow keras 对输入进行预处理
- html - 页面中有多个滑动菜单
- ios - 与具有多个子 ViewControllers 的 ViewController 交互
- java - 如何将我的程序重置为今天(Java)