spring - @ControllerAdvice 覆盖异常 @ResponseStatus

标签 spring spring-mvc spring-boot spring-annotations

我不知道为什么,但 @ControllerAdvice覆盖在 Exception 处定义的响应代码级别使用 @ResponseStatus注解。

异常(exception) :

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class GreetException extends RuntimeException {}

Controller :
@RestController
@RequestMapping("/")
public class GreetController {

    @RequestMapping(method = RequestMethod.GET)
    public String greet() {
        throw new GreetException();
    }
}

控制建议 :
@ControllerAdvice
public class ExceptionConfiguration {

    @ResponseStatus(HttpStatus.CONFLICT)
    @ExceptionHandler(RuntimeException.class)
    public void handleConflict() {}
}

当greet方法来自GreetController被调用响应是 409 - CONFLICT。因为我专门提供了异常级别的响应代码,所以我预计这将是返回的代码(400 - BAD_REQUEST)。
当然,这是一个过于简化的例子,但我们用 RuntimeException 定义了一个 Controller 建议。定义,以便我们可以为每个未捕获的异常分配一个 id。

实现预期行为的正确方法是什么?

最佳答案

@ResponseStatus 注释异常的问题也就是说,这仅在其他地方未处理异常时触发。

请参阅来自 Spring article about exception handling in Spring MVC 的引用:

When an annotated exception is thrown from a controller method, and not handled elsewhere, it will automatically cause the appropriate HTTP response to be returned with the specified status-code.



同一篇文章描述了尽管有 ControllerAdvice 使其工作的方法。与一般处理程序。见 Paragraph about ControllerAdvice .

如果异常用 @ResponseStatus 注释,您基本上要做的是在通用处理程序中重新抛出异常。 :
@ControllerAdvice
public class ExceptionConfiguration {

  @ResponseStatus(HttpStatus.CONFLICT)
  @ExceptionHandler(RuntimeException.class)
  public void handleConflict(RuntimeException e) throws RuntimeException {
    // Check for annotation
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
      // Rethrow Exception
      throw e;
    }
    else {
      // Provide your general exception handling here
    }
  }
}

关于spring - @ControllerAdvice 覆盖异常 @ResponseStatus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460932/

相关文章:

spring - Thymeleaf 如果在字符串上

java - 任何 java bean 中的 spring 依赖注入(inject)

java - Spring Boot 的 CORS 不在响应 header 中

javascript - AngularJS 两个日期之间的区别

java - Spring boot测试启动应用程序

java - @ConditionalOnBean 不适用于手动注册的 bean

java - 自定义@RequestParam返回消息和条件参数

java - 自定义注释,用于从 HttpServletRequest 获取具有指定 @RequestHeaders 集的自定义对象

java - Spring4 MVC Controller 可分页不起作用

spring-boot - Kotlin - 数据类实体抛出 StackOverflowError