在Java系统中,为了更清楚展示异常信息,通常需要自定义异常。
在exception包中,需要定义一个RestErrorResponse类与前端约定返回的异常信息模型。
@Data
public class RestErrorResponse implements Serializable{
private String errMessage;
public RestErrorResponse(errMessage){
this.errMessage = errMessage;
}
public String getErrMessage(){
return errMessage;
}
public void setErrMessage(){
this.errMessage = errMessage;
}
}
除此之外,我们可以写一个自定义异常类继承RuntimeException,重写构造方法。
public class DIYException extends RuntimeException{
private String errMessage;
public DIYException(){
}
public DIYException(String errMessage){
super(errMessage);
this.errMessage = errMessage;
}
public static void cast(String errMessage){
throw new RuntimeException(errMessage);
}
public static void cast(CommonError errMessage){
throw new RuntimeExceprion(errMessage);
}
}
一些通用的异常信息,可以通过创建枚举类实现。
public enum CommonError{
UNKNOW_ERROR("执行过程异常,请重试");
PARAMS_ERROR("非法参数");
OBJECT_NULL("对象为空");
QUERY_NULL("查询结果为空");
REQUEST_NULL("请求蚕食为空");
private String errMessage;
private String getErrMessage(){
return errMessage;
}
private CommonError(String errMessage){
this.errMessage = errMessage;
}
}
定义全局异常处理器
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler{
@Responsebody
@ExceptionHandler(DIYException.class)
@ResponseSttus(HttpStatus.INTERNAL.SERVER.ERROR)
public RestErrorResponse customException(DIYException e){
log.error("系统异常{}",e.getErrMessage(),e)
String errMessage = e.getErrMessage();
RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage);
return restErrorResponse;
}
@Responsebody
@ExceptionHandler(Exception.class)
@ResponseSttus(HttpStatus.INTERNAL.SERVER.ERROR)
public RestErrorResponse customException(Exception e){
log.error("系统异常{}",e.getMessage(),e)
RestErrorResponse restErrorResponse = new RestErrorResponse(CommonError.UNKNOWN_ERROR.getErrMessage());
return restErrorResponse;
}
}