java - Spring Boot 中的 NoSuchElementException @ExceptionHandler 不起作用

标签 java spring exceptionhandler

我在 Spring Boot 中创建了一个自定义异常处理程序:

@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。

我可能会遗漏一些非常微不足道的东西。将 NoSuchElementException 更改为 NotFoundException 没有任何区别。

最佳答案

您似乎不理解 @RestControllerAdvice Activity :

NOTE: @RestControllerAdvice is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace. RestControllerAdvice

使用@ControllerAdvice代替: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);
  }
}

关于java - Spring Boot 中的 NoSuchElementException @ExceptionHandler 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59945018/

相关文章:

java - 远程调试 Spring Boot 应用程序

java - Bean 验证范围约束

java - 为 OPTIONS 请求禁用自动 Wadl 生成

eclipse - 在 eclipse 中设置 Spring 和 Tomcat?

angularjs - $exceptionHandler 中的 $location - 依赖冲突

java - 使用@ExceptionHandler 根据请求动态返回 HTTP 状态代码

java - 使用 JAXB 和 MOXy 将 Java 属性映射到多个 xml 属性

java 二进制文件没有附带 openjdk-6-jdk 吗?

java - org.hibernate.exception.SQLGrammarException : could not prepare statement; nested exception is javax. 持久性.PersistenceException