Servlets 如何更改过滤器中的控制器响应,使响应结构在整个API中保持一致';他在用弹簧靴
我已经使用SpringBoot应用程序实现了RESTAPI。我所有的API现在都以JSON格式为每个实体返回响应。此响应被其他服务器使用,该服务器希望所有这些响应都使用相同的JSON格式。比如, 我的所有回答都应符合以下结构:Servlets 如何更改过滤器中的控制器响应,使响应结构在整个API中保持一致';他在用弹簧靴,servlets,spring-boot,filter,Servlets,Spring Boot,Filter,我已经使用SpringBoot应用程序实现了RESTAPI。我所有的API现在都以JSON格式为每个实体返回响应。此响应被其他服务器使用,该服务器希望所有这些响应都使用相同的JSON格式。比如, 我的所有回答都应符合以下结构: public class ResponseDto { private Object data; private int statusCode; private String error; private String message; }
public class ResponseDto {
private Object data;
private int statusCode;
private String error;
private String message;
}
目前,spring引导以不同的格式返回错误响应。如何使用过滤器实现这一点
错误消息格式
{
"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结构中这可以通过简单地使用和处理所有可能的异常,然后返回您自己选择的响应来实现
@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"
}
}
如何获取此handlethrowable()中的错误消息和错误代码method@Achaius很抱歉,我的示例写错了,您可以从参数获取消息到
handleThrowable()
方法,即本例中的throwable
。但无法确定状态代码,因为通过使用此结构,您将覆盖任何根据异常类型由Spring预先确定的状态代码。但大多数情况下,它将是500,因此您可以只给出状态代码500,其中包含本机异常的消息,而对于您自己的应用程序异常,您可以使用具有不同状态代码的单独处理程序。在servletFilterI中是否有这样做的方法我接受您的观点。但我担心的是状态码。无论如何,谢谢你的回复。我将尝试此解决方案,以避免显式的@ResponseBody
在每个方法中指定可以使用的@RestControllerAdvice