前言
上一篇SpringBoot 参数检验Assert使用了解了SpringBoot 参数检验Assert的使用,我们是不是可以自定义Assert,来实现自定义异常呢?
用 Assert(断言) 替换 throw exception
Assert.notNull(user, “用户不存在.”); 代替
throw new IllegalArgumentException(“用户不存在.”);
IResponseEnum
/**
* @author liu
* @date 2022年05月25日 11:16
*/
public interface IResponseEnum {
int getCode();
String getMessage();
}
异常最重要的两个信息code和message,为了表示不同的业务异常信息,采用枚举的方式
BaseException IResponseEnum作为BaseException属性
package com.andon.springbootdistributedlock.exception;
import com.andon.springbootdistributedlock.annotation.IResponseEnum;
import lombok.Data;
/**
* @author liu
* @date 2022年05月25日 11:14
*/
@Data
public class BaseException extends RuntimeException{
protected IResponseEnum responseEnum;
protected Object[] args;
public BaseException(IResponseEnum responseEnum){
super(responseEnum.getMessage());
this.responseEnum=responseEnum;
}
public BaseException(int code,String msg){
super(msg);
this.responseEnum=new IResponseEnum() {
@Override
public int getCode() {
return code;
}
@Override
public String getMessage() {
return msg;
}
};
}
public BaseException(IResponseEnum responseEnum,Object[] args,String message){
super(message);
this.responseEnum=responseEnum;
this.args=args;
}
public BaseException(IResponseEnum responseEnum,Object[] args,String message,Throwable cause){
super(message,cause);
this.responseEnum=responseEnum;
this.args=args;
}
}
全局异常引入IResponseEnum作为自己的属性,保证抛出的异常信息全部为服务自己定义。
自定义Assert
package com.andon.springbootdistributedlock.exception;
/**
* @author liu
* @date 2022年05月25日 11:12
*/
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);
}
}
}
定义BusinessExceptionAssert同时实现Assert判断逻辑和枚举类区分不同业务异常逻辑
package com.andon.springbootdistributedlock.exception;
import com.andon.springbootdistributedlock.annotation.IResponseEnum;
import java.text.MessageFormat;
/**
* @author liu
* @date 2022年05月25日 11:20
*/
public interface BusinessExceptionAssert extends IResponseEnum, Assert {
@Override
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
}
BusinessException
package com.andon.springbootdistributedlock.exception;
/**
* @author liu
* @date 2022年05月25日 11:19
*/
import com.andon.springbootdistributedlock.annotation.IResponseEnum;
import java.text.MessageFormat;
/**
* <p>业务异常</p>
* <p>业务处理时,出现异常,可以抛出该异常</p>
*/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
全局异常处理器
package com.andon.springbootdistributedlock.config;
import com.andon.springbootdistributedlock.domain.ResponseStandard;
import com.andon.springbootdistributedlock.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
/**
* 2021/11/10
* <p>
* 全局异常处理器
*/
@Slf4j
@RestControllerAdvice //对Controller增强,并返回json格式字符串
public class GlobalExceptionHandler {
/**
* 生产环境
*/
private final static String ENV_PROD = "prod";
/**
* 当前环境
*/
@Value("${spring.profiles.active}")
private String profile;
/**
* 捕获分布式锁异常,并自定义返回数据
*/
@ExceptionHandler(DistributedLockException.class)
public ResponseStandard<Object> distributedLockException(Exception e) {
return ResponseStandard.builder().code(-1).message(e.getMessage()).build();
}
/**
* Assert异常
*/
@ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseStandard<Object> exception(IllegalArgumentException e,HttpServletRequest request) {
log.error("request error!! method:{} uri:{}", request.getMethod(), request.getRequestURI());
String message = getExceptionDetail(e);
String message1 = e.getMessage();
return ResponseStandard.failureResponse(e.getMessage(),100);
}
/**
* Assert异常
*/
@ExceptionHandler(LoginException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseStandard<Object> exception(LoginException e,HttpServletRequest request) {
log.error("request error!! method:{} uri:{}", request.getMethod(), request.getRequestURI());
String message = getExceptionDetail(e);
String message1 = e.getMessage();
return ResponseStandard.failureResponse(e.getMessage(),e.getCode());
}
/**
* Assert异常
*/
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseStandard<Object> exception(BusinessException e,HttpServletRequest request) {
log.error("request error!! method:{} uri:{}", request.getMethod(), request.getRequestURI());
String message = getExceptionDetail(e);
String message1 = e.getMessage();
return ResponseStandard.failureResponse(e.getMessage(),e.getResponseEnum().getCode());
}
/**
* 获取代码报错详细位置信息
*/
public String getExceptionDetail(Exception e) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(e.getClass()).append(System.getProperty("line.separator"));
stringBuilder.append(e.getLocalizedMessage()).append(System.getProperty("line.separator"));
StackTraceElement[] arr = e.getStackTrace();
for (StackTraceElement stackTraceElement : arr) {
stringBuilder.append(stackTraceElement.toString()).append(System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
/**
* 自定义异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = BaseException.class)
@ResponseBody
public ResponseStandard handleBaseException(BaseException e) {
log.error(e.getMessage(), e);
//return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
return ResponseStandard.failureResponse(e.getMessage(),e.getResponseEnum().getCode());
}
/**
* Controller上一层相关异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler({
NoHandlerFoundException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
// BindException.class,
// MethodArgumentNotValidException.class
HttpMediaTypeNotAcceptableException.class,
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
MissingServletRequestPartException.class,
AsyncRequestTimeoutException.class
})
@ResponseBody
public ResponseStandard handleServletException(Exception e) {
log.error(e.getMessage(), e);
int code = ResponseEnum.SERVER_ERROR.getCode();
/*try {
ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName());
code = servletExceptionEnum.getCode();
} catch (IllegalArgumentException e1) {
log.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName());
}*/
if (ENV_PROD.equals(profile)) {
// 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
code = ResponseEnum.SERVER_ERROR.getCode();
BaseException baseException = new BaseException(ResponseEnum.SERVER_ERROR);
String message = e.getMessage();
ResponseStandard.failureResponse(e.getMessage(),code);
}
return ResponseStandard.failureResponse(e.getMessage(),code);
}
/**
* 参数绑定异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = BindException.class)
@ResponseBody
public ResponseStandard handleBindException(BindException e) {
log.error("参数绑定校验异常", e);
//ResponseStandard.failureResponse(e.getMessage(),code);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 参数校验异常,将校验失败的所有异常组合成一条错误信息
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public ResponseStandard handleValidException(MethodArgumentNotValidException e) {
log.error("参数绑定校验异常", e);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 包装绑定异常结果
*
* @param bindingResult 绑定结果
* @return 异常结果
*/
private ResponseStandard wrapperBindingResult(BindingResult bindingResult) {
StringBuilder msg = new StringBuilder();
for (ObjectError error : bindingResult.getAllErrors()) {
msg.append(", ");
if (error instanceof FieldError) {
msg.append(((FieldError) error).getField()).append(": ");
}
msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
}
//return new ErrorResponse(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2));
return ResponseStandard.failureResponse(msg.substring(2),ResponseEnum.VALID_ERROR.getCode());
}
/**
* 未定义异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseStandard handleException(Exception e,HttpServletRequest request) {
log.error(e.getMessage(), e);
log.error("request error!! method:{} uri:{}", request.getMethod(), request.getRequestURI());
if (ENV_PROD.equals(profile)) {
// 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
int code = ResponseEnum.SERVER_ERROR.getCode();
BaseException baseException = new BaseException(ResponseEnum.SERVER_ERROR);
String message = e.getMessage();
return ResponseStandard.failureResponse(message,ResponseEnum.VALID_ERROR.getCode());
}
return ResponseStandard.failureResponse(e.getMessage(),ResponseEnum.VALID_ERROR.getCode());
}
}
具体枚举类异常
package com.andon.springbootdistributedlock.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
/**
* @author liu
* @date 2022年05月25日 11:22
*/
@Getter
@AllArgsConstructor
public enum ResponseEnum implements BusinessExceptionAssert {
/**
* 用户不存在
*/
USER_NOT_FOUND(7000, "用户不存在."),
/**
* 未知异常
*/
SERVER_ERROR(9000, "未知异常."),
VALID_ERROR(8000, "校验异常.")
;
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
}
测试controller
package com.andon.springbootdistributedlock.controller;
import com.andon.springbootdistributedlock.domain.ResponseStandard;
import com.andon.springbootdistributedlock.dto.User;
import com.andon.springbootdistributedlock.exception.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liu
* @date 2022年05月25日 8:58
*/
@Slf4j
@RequestMapping(value = "/ex")
@RestController
public class TestExceptionController {
@PostMapping(value = "/test")
public ResponseStandard test(@RequestBody User user) throws Exception{
//通过用户名 查询用户
User user1 = getUser(user);
//int a = 1/0;
//Assert.notNull(user1, "用户不存在(Assert抛出)");
//AssertLogin.assertNotNull(user1, 100,"用户不存在(Assert抛出)");
ResponseEnum.USER_NOT_FOUND.assertNotNull(user1);
return ResponseStandard.successResponse("成功");
}
User getUser(User user){
return null;
}
}