上一篇rabbitmq集成和封装我们讲解rabbit相关的内容
本文项目源码地址:
在很多业务场景我们需要对一些异常情况进行异常抛出处理,但是抛出的异常往往在可读性上不是特别的友好。所以我们需要对异常进行处理。
在不同的业务场景我们需要对不同的的业务进行明确的异常说明,所以我们不能都抛出同一个runtimeException。这样表达就不够明确。所以整个异常的结构应该如下构建:
那么我们Com模块因为是公共的模块,所以整个项目体系的异常构建在Com模块中,项目异常定义如下:
/**
* 自定义异常的父类
* @author 大仙
*/
public class EduException extends RuntimeException {
private static final long serialVersionUID = -8879123682017730252L;
protected Integer code;
protected String title = "Online edu star Exception";
public EduException(String message) {
super(message);
}
public EduException(String message, int code) {
super(message);
this.code = code;
}
public EduException(String message, int code, String title) {
super(message);
this.code = code;
this.title = title;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
全局异常捕获处理
/**
* 全局异常捕获
* @author 大仙
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义异常
* @param ex
* @return
*/
@ExceptionHandler(EduException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ComResponse handleOrderException(EduException ex) {
return ComResponse.failResponse(null,ex.getCode()==null?500:ex.getCode(),ex.getMessage());
}
}
各个业务异常定义举例,例如认证异常:
/**
* 权限相关异常
* @author 大仙
*/
public class AuthException extends EduException {
public AuthException(String message) {
super(message);
}
public AuthException(String message, int code) {
super(message);
this.code = code;
}
public AuthException(String message, int code, String title) {
super(message);
this.code = code;
this.title = title;
}
}