【问题标题】:Spring 5 exception handling - ResponseStatusException modelSpring 5 异常处理——ResponseStatusException 模型
【发布时间】:2021-02-07 21:29:12
【问题描述】:

我正在阅读这篇文章 - https://www.baeldung.com/exception-handling-for-rest-with-spring 其中说

Spring 5 引入了 ResponseStatusException 类。

我们可以创建它的一个实例,提供一个 HttpStatus 和可选的 一个原因和一个原因:

我开始实现了,代码是

  1. 自定义异常
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Actor Not Found")
public class ActorNotFoundException extends Exception {
  private static final long serialVersionUID = 1L;
    
    public ActorNotFoundException(String errorMessage) {
      super(errorMessage);
    }
}
  1. 服务中的方法
public String updateActor(int index, String actorName) throws ActorNotFoundException {
  if (index >= actors.size()) {
    throw new ActorNotFoundException("Actor Not Found in Repsoitory");
  }
  actors.set(index, actorName);
  return actorName;
}
  1. 控制器
@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); //agreed it could be optional, but we may need original exception
  }
}

回购: https://github.com/eugenp/tutorials/tree/master/spring-5/src/main/java/com/baeldung/exception

问题:

为什么控制器中的 ResponseStatusException 再次必须指定原因 - “Actor Not Found”?正如服务已经说过的 - ““Actor Not Found in Repsoitory”

适应ResponseStatusException模型的正确方法是什么?

【问题讨论】:

  • 为什么不throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage(), ex); !? ;)
  • 可以直接抛出ResponseStatusException,也可以扩展。 Spring 也像这样重新定义了自己的异常,例如MethodNotAllowedException 现在扩展了 ResponseStatusException。

标签: spring spring-boot


【解决方案1】:

看起来是个错误。理想情况下,该服务不应使用任何 HTTP 代码,因此我将删除 ActorNotFoundException 中的注释。其他一切似乎都很好,异常被控制器捕获并抛出ResponseStatusException,这很好,因为它是放置 HTTP 内容的适当层。

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2019-10-11
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2023-03-28
    • 2016-10-31
    相关资源
    最近更新 更多