1.自定义异常抛出格式
继承自ResponseBodyAdvice
@Slf4j
@Order(1)
执行顺序优先级
@RestControllerAdvice(value = "com.fitmgr.ces")
指定包响应体都会受到拦截
public class ResponseBodyWrapper implements ResponseBodyAdvice {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
处理响应状态码为500 的异常
public RB handleGlobalException(Exception e) {
log.error("GOT SYS EXCEPTION: ", e);
return new RB<>(ReturnCodes.EXECUTE, ReturnCodes.EXECUTE.getMsg());
}
@ExceptionHandler(BaseException.class)
public RB handleGlobalException(BaseException exception, HttpServletResponse response) {
log.error("GOT INTERNAL EXCEPTION: ", exception);
response.setStatus(exception.getHttpStatus().value());
return new RB<>(exception.getCode(), exception.getMessage());
}
@ExceptionHandler(RestClientException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public RB handleGlobalException(RestClientException exception) {
log.error("GOT EXCEPTION: ", exception);
return new RB<>(ReturnCodes.EXECUTE, exception.getMessage());
}
@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public RB handleGlobalException(DuplicateKeyException exception) {
log.error("GOT DuplicateKeyException: ", exception);
return new RB<>(ReturnCodes.DUPLICATE_RESOURCE_EXCE, exception.getCause().getMessage());
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body == null) {
return new RB<>();
} else if (body instanceof RB) {
return body;
}
return new RB<>(body);
}
如果没有响应体则返回空的RB对象
如果响应体不是 RB对象则封装为RB对象
}