首页 > 解决方案 > 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.***

标签: javaspringexceptionhandler

解决方案


看起来你不了解@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);
  }
}

推荐阅读