在项目根包目录下新建 exception.base 包
新建BaseException 继承 RuntimeException
package com.ddz.errordemo.handler;
public class BaseException extends RuntimeException {
private String module;
private String code;
private Object[] args;
private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage) {
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BaseException(String module, String code, Object[] args) {
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage) {
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args) {
this(null, code, args, null);
}
public BaseException(String defaultMessage) {
this(null, null, null, defaultMessage);
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
public String getDefaultMessage() {
return defaultMessage;
}
public void setDefaultMessage(String defaultMessage) {
this.defaultMessage = defaultMessage;
}
}
根据自己的需要新建业务异常类
package com.ddz.errordemo.exception;
import com.ddz.errordemo.exception.base.BaseException;
public class UserException extends BaseException
{
private static final long serialVersionUID = 1L;
public UserException(String code, Object[] args)
{
super("user", code, args, null);
}
}
在项目根包目录下新建 exception.handler包;
新建RestExceptionHandler 异常处理类
package com.ddz.errordemo.exception.handler;
import com.ddz.errordemo.exception.base.BaseException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(Exception.class)
public Object exception(HttpServletRequest request, Exception e) {
return request.getRequestURL() + "全局异常" + e.getMessage();
}
@ExceptionHandler(NullPointerException.class)
public Object nullException(Exception e) {
return "空指针" + e.getMessage();
}
@ExceptionHandler(RuntimeException.class)
public Object busException(BaseException e) {
return "模块" + e.getModule() + "异常码:" + e.getCode() + "异常信息:" + e.getMessage();
}
}



