【转载】SpringBoot统一异常处理最佳实践
写的真的好,掘金的质量真的高,实名点赞一波。
https://juejin.im/post/5c3ea92a5188251e101598aa
这是我之前写的统一响应结果集:
public class ResponseResult { //状态码 private int status; //消息 private String message; //返回数据 private Object data; public ResponseResult() { } public ResponseResult(int status, String message, Object data) { this.status = status; this.message = message; this.data = data; } //成功 public static ResponseResult success(Object data){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,"success",data); } public static ResponseResult success(String message){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,message,null); } public static ResponseResult success(){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,"success",null); } //失败 public static ResponseResult fail(){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,"fail",null); } public static ResponseResult fail(Object data){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,"fail",data); } public static ResponseResult fail(String message){ return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,message,null); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
常量定义:
public interface ResponseStatusConstant { /** * 响应状态码,1表示成功 */ public static final int RESPONSE_STATUS_SUCCESS=1; /** * 响应状态码,2表示成功 */ public static final int RESPONSE_STATUS_FAIL=2; /** * 响应状态码,3表示没有权限 */ public static final int RESPONSE_STATUS_NO_PERMISSION=3; }
总之,一定要面向切面(AOP)的思想。