现在公司开发基本上都是以前后分离模式为主,所以要有个统一的数据格式,这样有什么好处呢?
这里我就初步定了两种异常状态码,更多状态码可以根据自己的情况去定义
@Getter public enum ResponseEnum { SUCCESS(0, "OK"), PARAMETER_ERROR(1,"参数异常"), SYSTEM_ERROR(500, "服务器异常,请联系管理员"); ResponseEnum(Integer code, String message) { this.code = code; this.message = message; } private final Integer code; private final String message; }
注意:这里data最好使用泛型,如果使用的object,那么swagger接口文档将无法显示对应的字段属性定义
public class ResponseModel<T> { private Integer code; private String message; private T data; public ResponseModel(Integer code, String message, T data) { this.code = code; this.message = message; this.data = data; } public static ResponseModel<Void> ok() { return ok(null); } public static <T> ResponseModel<T> ok(T data) { return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage(), data); } public static <T> ResponseModel<T> ok(T data, String message) { return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), message, data); } public static ResponseModel<Void> error(Integer statusCode, String message) { return new ResponseModel<>(statusCode, message, null); } public static ResponseModel<Void> error(String message) { return error(ResponseEnum.SYSTEM_ERROR.getCode(), message); } public static ResponseModel<Void> error() { return error(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage()); } }
这里没啥好说的,自定义个异常继承RuntimeException
,加上状态码属性
@Getter public class BusinessException extends RuntimeException { private Integer code; public BusinessException(Integer code, String message) { super(message); this.code = code; } public BusinessException(String message) { super(message); } }
@ControllerAdvice @ResponseBody @Slf4j public class GlobalException { @ExceptionHandler(value = BusinessException.class) public ResponseModel<Void> BusinessExceptionError(BusinessException e) { log.error("业务异常", e); if (e.getCode() != null) { return ResponseModel.error(e.getCode(), e.getMessage()); } return ResponseModel.error(e.getMessage()); } @ExceptionHandler(value = Exception.class) public ResponseModel<Void> ExceptionError(Exception e) { log.error("系统异常", e); return ResponseModel.error(); } }
如果不用通过返回的话,这里还需要进行异常捕获,而采用统一异常直接return即可,自定义异常直接抛出,有统一异常可以进行处理
//controller层 @ResponseBody @PostMapping("/test") public ResponseModel<Void> save() throws Exception { // 业务操作 return ResponseModel.ok(); } //service public void save(String name) throws Exception { if(name == null){ throw new BusinessException(ResponseEnum.PARAMETER_ERROR.getCode(),ResponseEnum.PARAMETER_ERROR.getMessage()); } }
访问服务不存在的接口404时,是无法进行捕获的,这个问题小伙伴们可以阅读我之后更新的文章会进行处理
感谢各位小伙伴阅读到最后,如有错误,敬请指正。