一个项目在运行过程中必定会产生异常的,那么异常处理就是必须的。一个结构良好的异常类,对于快速定位产生的bug是非常有利的。
1.异常枚举类
public enum SysExceptionEnum {
/**
* 枚举异常码
*/
INTERNAL_ERROR("501", "系统内部异常"),
ILLEGAL_PARAM("502", "请求参数不合法"),
SQL_ERROR("503", "数据库操作异常,字段不合格或者主键冲突等!"),
;
/**
* 私有枚举构造参数和构造函数
*/
private String code;
private String message;
SysExceptionEnum(String code, String message) {
this.code = code;
this.message = message;
}
/**
* 通过code找枚举的方法
*/
public static SysExceptionEnum get(Long code){
for (SysExceptionEnum result : values()){
if (result.getCode().equals(code)){
return result;
}
}
return null;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
2.自定义异常
*继承了RuntimeException
public class SystemException extends RuntimeException {
private String code ;
private String message;
public SystemException(String code,String message) {
super(message);
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
到此步其实已经可以使用自定异常了,写个测试类测试
public class Test {
public static void main(String[] args){
throw new SystemException(SysExceptionEnum.INTERNAL_ERROR.getCode(),
SysExceptionEnum.INTERNAL_ERROR.getMessage());
}
}
异常测试
4.统一异常抛出类
进一步封装异常抛出
public class LeaseException {
public static void throwSystemException(SysExceptionEnum sysExceptionEnum) {
try {
throw new SystemException(sysExceptionEnum.getCode(), sysExceptionEnum.getMessage());
}catch (SystemException e){
e.printStackTrace();
}
}
}
5.在Spring项目中配套使用统一异常返回处理
@Controller
@ControllerAdvice
public class BaseController {
protected <T> ResponseObject<T> success(T dataObject) {
return new ResponseObject<>(dataObject);
}
protected ResponseObject success(){
return new ResponseObject();
}
@ExceptionHandler
public @ResponseBody
ResponseObject exceptionHandler(HttpServletRequest request, HttpServletResponse httpResponse, Exception ex) {
ResponseObject responseObject = new ResponseObject() ;
ex.printStackTrace();
try {
if(ex instanceof SystemException) {//自定义异常提示
SystemException systemException = (SystemException) ex;
responseObject.setMessage(systemException.getMessage());
responseObject.setCode(systemException.getCode());
return responseObject;
}else if( ex instanceof DataAccessException){//数据库操作异常
responseObject.setMessage(SysExceptionEnum.SQL_ERROR.getMessage());
responseObject.setCode(SysExceptionEnum.SQL_ERROR.getCode());
return responseObject;
}else{
responseObject.setMessage(SysExceptionEnum.INTERNAL_ERROR.getMessage());
responseObject.setCode(SysExceptionEnum.INTERNAL_ERROR.getCode());
return responseObject;
}
} catch (Exception e) {//其他系统内部异常
responseObject.setMessage(SysExceptionEnum.INTERNAL_ERROR.getCode());
responseObject.setCode(SysExceptionEnum.INTERNAL_ERROR.getMessage());
return responseObject;
}
}
}
网友评论