ResponseBodyAdvice
@RestControllerAdvice(basePackages = {"com.by"})@Slf4j
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
@ExceptionHandler(Exception.class)
public Object processException(Exception ex){
ResponseDto responseDto = new ResponseDto();
responseDto.setCode(1);
responseDto.setMessage(ex.getMessage());
return responseDto;
}
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(body instanceof ResponseDto){
return body;
}
ResponseDto responseDto = new ResponseDto();
responseDto.setCode(0);
responseDto.setMessage("请求成功");
responseDto.setData(body);
if (selectedConverterType == StringHttpMessageConverter.class) {
return JSONUtil.toJsonStr(responseDto);
} else {
return responseDto;
}
}
}