【问题标题】:Customize Spring Boot error response code without changing the default body在不更改默认正文的情况下自定义 Spring Boot 错误响应代码
【发布时间】: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


    【解决方案1】:

    事实证明,我提到的问题this answer 具有解决此问题所需的确切解决方案,即使它并没有完全解决问题。诀窍是从方法中删除@ResponseStatus 的使用,并使用HttpServletResponse.sendError() 手动设置HttpServletResponse 的状态。这服务于标准 Spring Boot 异常响应,但具有更新的状态代码。

    @ExceptionHandler
    public void handleEntityNotFoundException(EntityNotFoundException e, HttpServletResponse response) throws IOException {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    
    {
        "timestamp": 1587794161453,
        "status": 404,
        "error": "Not Found",
        "exception": "javax.persistence.EntityNotFoundException",
        "message": "No resource exists for the given ID",
        "path": "/my-resource/1"
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2016-09-09
      • 2015-05-20
      • 2014-12-01
      • 2017-08-08
      • 2019-08-13
      • 2015-09-04
      • 2017-03-08
      相关资源
      最近更新 更多