Springboot 自定义全局异常处理
自定义全局异常处理
- 业务异常
- 捕捉validation框架校验异常
业务异常
在项目根包目录下新建 exception.base 包
新建BaseException 继承 RuntimeException
package com.ddz.errordemo.handler;
/**
* 基础异常类
* @author Lenovo
* @date 2022/4/26
*/
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;
/**
* @author Lenovo
* @date 2022/4/26
*/
@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();
}
}
捕捉validation框架校验异常
如果springboot 版本高于3.5.1 需要导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
在异常类中添加方法
import com.ddz.project.common.exception.code.BusinessException;
import com.ddz.project.common.exception.code.BaseResponseCode;
import com.ddz.project.common.exception.code.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
/**
* RestExceptionHandler
*
* @author Lenovo
* @version V1.0
* @date 2020年3月18日
*/
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
/**
* 自定义全局异常处理
*/
@ExceptionHandler(value = BusinessException.class)
Object businessExceptionHandler(BusinessException e) {
log.error("BusinessException:{}", e.getMessageCode(), e);
return e.getMessageCode()+e.getDetailMessage();
}
/**
* 处理validation 框架异常, 需要controller添加@Validated注解
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
Object methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
List<ObjectError> errors = e.getBindingResult().getAllErrors();
// String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
return errors.get(0).getDefaultMessage();
}
/**
* 校验List<entity>类型, 需要controller添加@Validated注解
* 处理Validated List<entity> 异常
*/
@ExceptionHandler
public Object handle(ConstraintViolationException exception) {
log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", exception, exception);
Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
StringBuilder builder = new StringBuilder();
for (ConstraintViolation<?> violation : violations) {
builder.append(violation.getMessage());
break;
}
return builder.toString();
}
}
还没有评论,来说两句吧...