#全局异常的处理封装
##返回结果类封装:
public class Result {
//是否成功
private Boolean success;
//状态码
private Integer code;
//提示信息
private String msg;
//数据
private Object data;
public Result() {
}
//自定义返回结果的构造方法
public Result(Boolean success,Integer code, String msg,Object data) {
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
//自定义异常返回的结果
public static Result defineError(BusinessException de){
Result result = new Result();
result.setSuccess(false);
result.setCode(de.getErrorCode());
result.setMsg(de.getErrorMsg());
result.setData(null);
return result;
}
//其他异常处理方法返回的结果
public static Result otherError(ErrorEnum errorEnum){
Result result = new Result();
result.setMsg(errorEnum.getMsg());
result.setCode(errorEnum.getCode());
result.setSuccess(false);
result.setData(null);
return result;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
##自定义异常类:
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 错误状态码
*/
protected Integer errorCode;
/**
* 错误提示
*/
protected String errorMsg;
public BusinessException(){
}
public BusinessException(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
##枚举,拒绝硬编码:
public enum SystemEnum {
SUCCESS(200, "操作成功"),
NO_PERMISSION(403,"你没有权限"),
NO_AUTH(401,"未登录,请先登录"),
NOT_FOUND(404, "未找到该资源!"),
INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),
;
private Integer code;
private String msg;
SystemEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
##全局异常处理类:
/**
* 全局异常处理器
*
*/
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理自定义异常
*
*/
@ExceptionHandler(value = BusinessException.class)
public Result bizExceptionHandler(BusinessException e) {
logger.error(e.getMessage(), e);
return Result.defineError(e);
}
/**
* 处理其他异常
*
*/
@ExceptionHandler(value = Exception.class)
public Result exceptionHandler( Exception e) {
logger.error(e.getMessage(), e);
return Result.otherError(SystemEnum.INTERNAL_SERVER_ERROR);
}
}
结束,大家可以自己测试,指出不足(测试时从controller中抛出自定义异常)。