【问题标题】:How to change controller response in filter to make the response structure consistent all over the API's using spring-boot如何使用 spring-boot 更改过滤器中的控制器响应以使响应结构在整个 API 中保持一致
【发布时间】:2017-08-21 23:36:42
【问题描述】:

我已经使用 spring-boot 应用程序实现了 REST API。我所有的 API 现在都以 JSON 格式为每个实体返回响应。此响应已被其他服务器消耗,该服务器期望所有这些响应都采用相同的 JSON 格式。例如;

我的所有回复都应包含在以下结构中;

public class ResponseDto {
    private Object data;
    private int statusCode;
    private String error;
    private String message;
}

目前 spring-boot 以不同的格式返回错误响应。如何使用过滤器实现这一点。

错误信息格式;

{
   "timestamp" : 1426615606,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/welcome",
   "message" : "Required String parameter 'name' is not present"
}

我的 spring-boot 应用程序中的错误和成功响应都需要在相同的 json 结构中

【问题讨论】:

    标签: servlets spring-boot filter


    【解决方案1】:

    这可以通过使用ControllerAdvice 并处理所有可能的异常,然后返回您自己选择的响应来实现。

    @RestControllerAdvice
    class GlobalControllerExceptionHandler {
    
        @ResponseStatus(HttpStatus.OK)
        @ExceptionHandler(Throwable.class)
        public ResponseDto handleThrowable(Throwable throwable) {
            // can get details from throwable parameter
            // build and return your own response for all error cases.
        }
    
        // also you can add other handle methods and return 
        // `ResponseDto` with different values in a similar fashion
        // for example you can have your own exceptions, and you'd like to have different status code for them
    
        @ResponseStatus(HttpStatus.OK)
        @ExceptionHandler(CustomNotFoundException.class)
        public ResponseDto handleCustomNotFoundException(CustomNotFoundException exception) {
            // can build a "ResponseDto" with 404 status code for custom "not found exception"
        }
    }
    

    Some great read on controller advice exception handlers

    【讨论】:

    • 我应该如何在这个 handlethrowable() 方法中得到错误信息和错误代码
    • @Achaius 对不起我写错了我的例子,你可以从handleThrowable()方法的参数中获取消息,在这个例子中就是throwable。但是无法确定状态代码,因为通过使用此结构,您将覆盖 Spring 根据异常类型预先确定的任何状态代码。但大多数情况下它将是 500,因此您可以只为本地异常提供状态码 500,而对于您自己的应用程序异常,您可以使用具有不同状态码的单独处理程序。
    • 有没有办法在 servletFilter 中做到这一点
    • 我接受你的观点。但我担心的是状态码。无论如何感谢您的回复。我会试试这个解决方案
    • 为了避免在每个方法中明确指定@ResponseBody,可以使用@RestControllerAdvice来代替
    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 2020-08-11
    • 2020-08-01
    • 2019-01-15
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多