我使用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结构中
答案 0 :(得分: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"
}
}