Respect 巨人大哥:https://www.cnblogs.com/jurendage/p/11255197.html
源码:结构
maven pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
package com.boot.commons.exception.base;
public interface Assert {
/**
* 创建异常
*
* @param args
* @return
*/
BaseException newException(Object... args);
/**
* 创建异常
*
* @param t
* @param args
* @return
*/
BaseException newException(Throwable t, Object... args);
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
*
* @param obj 待判断对象
*/
default void assertNotNull(Object obj) {
if (obj == null) {
throw newException(obj);
}
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param obj 待判断对象
* @param args message占位符对应的参数列表
*/
default void assertNotNull(Object obj, Object... args) {
if (obj == null) {
throw newException(args);
}
}
}
package com.boot.commons.exception.base;
import lombok.Data;
/**
* spring 对于 RuntimeException 异常才会进行事务回滚
*/
@Data
public class BaseException extends RuntimeException {
// 错误code和message接口对象
private IResponseEnum responseEnum;
// 针对国际化配置异常提示信息的处理。根据实现了IResponseEnum的枚举类,获取对应的"前缀."+类名的方式获取对应的配置信息,进行文本内容的填充,
// 例如:response.BAD_LICENCE_TYPE=Bad licence type{0},args参数指定了具体的填充信息。
private Object[] args;
// 默认错误信息
private String message;
public BaseException(IResponseEnum responseEnum) {
super(responseEnum.getMessage());
this.responseEnum = responseEnum;
}
public BaseException(IResponseEnum responseEnum, Object[] args, String message) {
super(message);
this.responseEnum = responseEnum;
this.args = args;
this.message = message;
}
public BaseException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(message, cause);
this.responseEnum = responseEnum;
this.args = args;
this.message = message;
}
}
package com.boot.commons.exception.base;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor