【问题标题】:When to use ResponseStatusException and ControllerAdvice何时使用 ResponseStatusException 和 ControllerAdvice
【发布时间】:2021-07-20 13:06:15
【问题描述】:

Spring5 引入了 ResponseStatusException,这让我陷入了两难的境地,即我可以在什么情况下使用 ResponseStatusException 和 ControllerAdvice,因为它们非常相似。

谁能帮我解决这个问题。 提前致谢。

【问题讨论】:

    标签: exception error-handling response httpresponse controller-advice


    【解决方案1】:

    让我们先了解什么是 ResponseStatusException 和 ControllerAdvice

    ResponseStatusException 是@ResponseStatus 的编程替代方案,是用于将状态代码应用于 HTTP 响应的异常的基类。

    @GetMapping("/actor/{id}")
    public String getActorName(@PathVariable("id") int id) {
        try {
            return actorService.getActor(id);
        } catch (ActorNotFoundException ex) {
            throw new ResponseStatusException(
              HttpStatus.NOT_FOUND, "Actor Not Found", ex);
        }
    }
    

    @ControllerAdvice 注释允许我们将多个分散的@ExceptionHandler 合并到一个单一的全局错误处理组件中。

    @ControllerAdvice
    public class RestResponseEntityExceptionHandler 
      extends ResponseEntityExceptionHandler {
    
        @ExceptionHandler(value 
          = { IllegalArgumentException.class, IllegalStateException.class })
        protected ResponseEntity<Object> handleConflict(
          RuntimeException ex, WebRequest request) {
            return ResponseEntity<Object>;
        }
    }
    

    回到您关于何时使用什么的问题:

    1. 如果你想提供一个统一和全局的异常处理方式,请使用 控制器建议。它还消除了可能由 ResponseStatusException 引起的代码重复。
    2. 为了对同一异常抛出不同的错误代码和响应,不要创建自定义异常类并避免紧密耦合,请使用 ResponseStatusException。

    参考资料:

    1. Spring ResponseStatusException

    2. Error Handling for REST with Spring

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 1970-01-01
      • 2022-11-04
      • 2014-09-06
      • 1970-01-01
      • 2018-04-07
      • 2020-10-15
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多