【问题标题】:Change responseStatusCode when returning customer Exception object返回客户异常对象时更改 responseStatusCode
【发布时间】:2020-06-01 07:54:08
【问题描述】:

我使用 Spring Boot 构建了一个 rest API,当使用我创建的类 xxEntity 发生异常时返回一个自定义 ResponseEntity

public class xxEntity<T> {
    private T body;
    private HttpStatus status;
    private int statusCode;
    private xxException error;

    public xxEntity(T body) {
        this.body = body;
        status = HttpStatus.OK;
        this.statusCode = status.value();
    }

    public xxEntity(HttpStatus status, xxException error) {
        this.status = status;
        this.statusCode = status.value();
        this.error = error;
    }
}

当出现异常时,我将实体返回如下:

return new xxEntity<>(HttpStatus.NOT_FOUND, new xxException(ex));

其中ex 是一个包含Stringfrench 消息、Stringenglish 消息和intinternal 错误代码的json。

它返回一个包含以下详细信息的自定义对象:

{
    "body": null,
    "status": "NOT_FOUND",
    "statusCode": 404,
    "error": {
        "userMessage": {
            "en": "No user found",
            "fr": "Pas d'utilisateur trouvé",
            "errorCode": 10
        }
    }
}

直到一切正常,唯一的问题是我只能返回状态码 200 OK

我其实是想根据发生的事件返回不同的状态码,这样前端就可以很容易的将其作为异常处理,而无需编写多个 if..else 条件

示例:实际上在我附加的 json 中,状态代码是 404 NOT FOUND,但是在邮递员中发出请求时,我收到 200 OK

【问题讨论】:

    标签: java spring-boot exception http-status-codes


    【解决方案1】:

    最好的方法是使用 controllerAdvice。这是一个用 @ControllerAdvice 注释的类,您可以在其中为要管理的每种异常类型定义方法,该函数的结果是 api 的响应,我的意思是 httpstatus 以及您想要的 bosy。

    除了这个解决方案之外,您还可以在控制器类中的错误处理程序方法中使用其他方法,例如使用@ExceptionHandler。但我认为最干净的方法是使用 ControllerAdvice。

    无论如何,在这里您可以找到在 Spring Rest API 中管理异常的所有方法的示例

    https://www.baeldung.com/exception-handling-for-rest-with-spring

    【讨论】:

      【解决方案2】:

      HttpStatus 代码作为响应对象的一部分返回。你可能需要做这样的事情 ->

      ResponseEntity.status(HttpStatus.NOT_FOUND).body();

      查看开源项目 - response-builder,它是构造自定义 api 响应和异常处理的包装器 -> https://github.com/AccessGateLabs/response-builder

      【讨论】:

        【解决方案3】:

        如果你使用 sprint 5,你可以试试:

        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Foo Not Found", exc);
        

        在您的控制器中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-24
          • 2017-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-22
          相关资源
          最近更新 更多