【发布时间】:2021-02-07 21:29:12
【问题描述】:
我正在阅读这篇文章 - https://www.baeldung.com/exception-handling-for-rest-with-spring 其中说
Spring 5 引入了 ResponseStatusException 类。
我们可以创建它的一个实例,提供一个 HttpStatus 和可选的 一个原因和一个原因:
我开始实现了,代码是
- 自定义异常
@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);
}
}
- 服务中的方法
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;
}
- 控制器
@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