上一篇SpringBoot 参数检验Assert使用了解了SpringBoot 参数检验Assert的使用,我们是不是可以自定义Assert,来实现自定义异常呢?
Assert.notNull(user, “用户不存在.”); 代替
throw new IllegalArgumentException(“用户不存在.”);
/**
* @author liu
* @date 2022年05月25日 11:16
*/
public interface IResponseEnum {
int getCode();
String getMessage();
}
异常最重要的两个信息code和message,为了表示不同的业务异常信息,采用枚举的方式
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作为自己的属性,保证抛出的异常信息全部为服务自己定义。
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);
/**
* 断言对象obj
非空。如果对象obj
为空,则抛出异常
*
* @param obj 待判断对象
*/
default void assertNotNull(Object obj) {
if (obj == null) {
throw newException(obj);
}
}
/**
*
断言对象obj
非空。如果对象obj
为空,则抛出异常
*
异常信息message
支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param obj 待判断对象
* @param args message占位符对应的参数列表
*/
default void assertNotNull(Object obj, Object... args) {
if (obj == null) {
throw newException(args);
}
}
}
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);
}
}
package com.andon.springbootdistributedlock.exception;
/**
* @author liu
* @date 2022年05月25日 11:19
*/
import com.andon.springbootdistributedlock.annotation.IResponseEnum;
import java.text.MessageFormat;
/**
* 业务异常
* 业务处理时,出现异常,可以抛出该异常
*/
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
*
* 全局异常处理器
*/
@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
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;
}
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;
}
}