【发布时间】:2020-08-08 19:58:35
【问题描述】:
默认情况下,Spring Boot 会为满足我开箱即用需求的异常返回响应正文:
{
"timestamp": 1587794161453,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.persistence.EntityNotFoundException",
"message": "No resource exists for the given ID",
"path": "/my-resource/1"
}
但是,我想为我的应用程序抛出的不同类型的异常自定义响应代码。有些异常不是我拥有的,所以我不能只在异常类上粘贴@ResponseStatus 注释。我尝试使用@ExceptionHandler 和@ResponseStatus 方法,但这会覆盖响应正文,这是我不希望发生的。例如,我想映射 javax.persistence.EntityNotFoundException 以返回状态码 404。
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleEntityNotFoundException(EntityNotFoundException e) {
// This method returns an empty response body
}
This question 与我的类似,但它也在尝试调整响应正文。我希望有一种更短、更惯用的方式来调整状态码而不是正文。
【问题讨论】:
标签: java spring spring-boot spring-mvc exception