spring 自定义 ExcePtion
2019-08-12 本文已影响0人
才不是小小喵
- 自定义定义一个异常处理类 继承RuntimeException
public class BusinessExcePtion extends RuntimeException {
//业务异常
public static final String DEFAULT_ERR_MSG = "服务器异常";
private String code;
public BusinessExcePtion() {
super(DEFAULT_ERR_MSG);
this.code = BusinessExcePtionEnums.DEFAULT_ERR_CODE.code;
}
public BusinessExcePtion(String message) {
super(message);
this.code = BusinessExcePtionEnums.RECORD_NOT_EXISTS.code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
- 定义你得code错误码
public enum BusinessExcePtionEnums {
/**
* 服务器异常
*/
DEFAULT_ERR_CODE("-99999"),
/**
* 请求参数不合法
**/
ILLEGAL_PARAMETER("-88888"),
/**
* 非法状态
**/
ILLEGAL_STATUS("-99997"),
/**
* 查询记录不存在
**/
RECORD_NOT_EXISTS("-99999"),
SUCCESS("200");
public static final String ERROR_PREFIX = "error.msg.";
public final String code;
BusinessExcePtionEnums(String s) {
code = s;
}
}
- spring aop特性拦截系统返回
@ControllerAdvice
@ResponseBody
public class ExceptionHandle {
@ExceptionHandler(value = BusinessExcePtion.class)
public ExceptionResponse defaultErrorHandler(HttpServletRequest req, BusinessExcePtion e) {
return new ExceptionResponse(e.getCode(), e.getMessage());
}
}
- 自定义返回bean
@Data
public class ExceptionResponse {
private String code ;
private String msg = "";
public ExceptionResponse() {
}
public ExceptionResponse(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
- OK 现在可以试着用一下了
throw new BusinessExcePtion("XXXXXX");