Generally, the api interface returned to the front end is unified
But if the front-end operation is wrong, the back-end return code is 400, and the http status code is still 200.
How to achieve uniform return code is 400?
Especially for front-end projects for SSR.
Solution: Use the interceptor ResponseBodyAdvice to achieve unified interception
Spring opens the ResponseBodyAdvice interface to allow interception and access to ResponseBody .
Function of the method:
supports: Specify whether to intercept
beforeBodyWrite: Execute the interception logic
package com.xxx.common;
/**
* 响应http状态码统一修改
*/
@ControllerAdvice
public class HttpStatusCodeAdvice implements ResponseBodyAdvice {
/**
* 指定是否进行拦截
* @param returnType
* @param converterType
* @return
*/
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return returnType.getParameterType().isAssignableFrom(ApiRestResponse.class);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//取出后端响应结果 修改http状态码
if(body != null) {
int code = (int) ((ApiRestResponse) body).getCode();
response.setStatusCode(HttpStatus.valueOf(code));
}
return body;
}
}
Refer to this post: