/**
* 自定义错误码
*/
public enum ErrorEnum {
// 数据操作错误定义
SUCCESS(200, "nice"),
NO_PERMISSION(403,"你没得权限"),
NO_AUTH(401,"你能不能先登录一下"),
NOT_FOUND(404, "未找到该资源!"),
INTERNAL_SERVER_ERROR(500, "服务器跑路了"),
;
/** 错误码 */
private Integer errorCode;
/** 错误信息 */
private String errorMsg;
ErrorEnum(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
/**
* 自定义异常
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BizException extends RuntimeException{
protected Integer errorCode;
protected String errorMsg;
public BizException(ErrorEnum errorEnum) {
this.errorCode=errorEnum.getErrorCode();
this.errorMsg=errorEnum.getErrorMsg();
}
public BizException(ErrorEnum errorEnum,String errorMsg) {
this.errorCode=errorEnum.getErrorCode();
this.errorMsg=errorMsg;
}
}
/**
* 封装http返回结果
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
//是否成功
private Boolean success;
//状态码
private Integer code;
//提示信息
private String msg;
//数据
private T data;
//自定义异常返回的结果
public static Result bizError(BizException be){
Result result = new Result();
result.setSuccess(false);
result.setCode(be.getErrorCode());
result.setMsg(be.getErrorMsg());
result.setData(null);
return result;
}
//其他异常处理方法返回的结果
public static Result otherError(Exception e){
Result result = new Result();
result.setMsg(e.getMessage());
result.setCode(500);
result.setSuccess(false);
result.setData(null);
return result;
}
}
/**
*全局异常捕获与处理
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
/**
* 处理自定义异常
*
*/
@ExceptionHandler(value = BizException.class)
public Result bizExceptionHandler(BizException e) {
return Result.bizError(e);
}
/**
* 处理其他异常
*
*/
@ExceptionHandler(value = Exception.class)
public Result exceptionHandler( Exception e) {
return Result.otherError(e);
}
}
|