【问题标题】:NoSuchElementException @ExceptionHandler in SpringBoot not workingSpringBoot 中的 NoSuchElementException @ExceptionHandler 不起作用
【发布时间】:2020-01-28 08:50:40
【问题描述】:

我在 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.***

【问题讨论】:

标签: java spring exceptionhandler


【解决方案1】:

您似乎没有理解@RestControllerAdvice 活动。

注意:如果配置了适当的 HandlerMapping-HandlerAdapter 对,例如 MVC Java 配置和 MVC 命名空间中默认的 RequestMappingHandlerMapping-RequestMappingHandlerAdapter 对,则处理 @RestControllerAdvice。 RestControllerAdvice

请改用@ControllerAdviceControllerAdvice

您有一个 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);
  }
}

【讨论】:

  • 你能简单解释一下吗?
  • 我认为你没有理解这个问题。我无处要求回复。
  • @Rishi move public final void with protected ResponseEntity&lt;Object&gt;
  • 做到了..还在那里。 :(
猜你喜欢
  • 2021-05-22
  • 2018-12-10
  • 1970-01-01
  • 2016-10-02
  • 2015-05-06
  • 1970-01-01
  • 2017-08-03
  • 2018-12-08
  • 1970-01-01
相关资源
最近更新 更多