如何在过滤器中更改控制器响应,以使响应结构在整个API中使用spring-boot保持一致

Ach*_*ius 5 servlets filter spring-boot

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

我的所有答复都应纳入以下结构;

public class ResponseDto {
    private Object data;
    private int statusCode;
    private String error;
    private String message;
}
Run Code Online (Sandbox Code Playgroud)

目前,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"
}
Run Code Online (Sandbox Code Playgroud)

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

bur*_*ete 4

这可以简单地通过利用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"
    }
}
Run Code Online (Sandbox Code Playgroud)

关于控制器建议异常处理程序的一些精彩读物