1、平时在项目中抛出异常
if (CollectionUtils.isEmpty(templateModelList)) {
throw new RuntimeException("评测信息不能为空!");
}
缺点:每次判断后,都要new一个异常类,抛出异常,代码重复,并且重复new 对象
2、真正在项目中抛出异常
1、自定义异常工具类
这个工具类,可以判断集合、数组、对象等为空的情况
/**
* 断言工具类
*/
public class BizExceptionAssert {
private BizExceptionAssert(){}
public static void isTrue(boolean expression, BizErrorCodeEnum errorCode) {
if (!expression) {
throw new BizException(errorCode);
}
}
public static void isTrue(boolean expression, BizErrorCodeEnum errorCode, String message) {
if (!expression) {
throw new BizException(errorCode, message);
}
}
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new BizException(message);
}
}
public static void notNull(Object object, String message) {
if (object == null) {
throw new BizException(message);
}
}
public static void notBlank(String text, String message) {
if (StringUtils.isBlank(text)) {
throw new BizException(message);
}
}
public static void notEmpty(Object[] array, String message) {
if (ArrayUtils.isEmpty(array)) {
throw new BizException(message);
}
}
public static void noNullElements(Object[] array, String message) {
if (array != null) {
for (Object element : array) {
if (element == null) {
throw new BizException(message);
}
}
}
}
public static void notEmpty(Collection<?> collection, String message) {
if (CollectionUtils.isEmpty(collection)) {
throw new BizException(message);
}
}
public static void notEmpty(Map<?, ?> map, String message) {
if (MapUtils.isEmpty(map)) {
throw new BizException(message);
}
}
}
2、在程序中使用
如果skuList为空,就抛出异常信息“”
BizExceptionAssert.notEmpty(skuList,"商品sku详情信息为空");
3、在定义全局异常的类中捕获BizException异常
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常捕捉处理
*
* @param e
* @param request
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ResponseResult errorHandler(Exception e, HttpServletRequest request) {
e.printStackTrace();
return ResultUtils.failure("系统繁忙");
}
// 捕获runtimeException异常
@ResponseBody
@ExceptionHandler(value = RuntimeException.class)
public ResponseResult errorHandler(RuntimeException e, HttpServletRequest request) {
return ResultUtils.failure(e.getMessage());
}
// 处理BizException异常
@ResponseBody
@ExceptionHandler(value = BizException.class)
public ResponseResult errorHandler(BizException e, HttpServletRequest request) {
return ResultUtils.failure(e.getCode(),e.getMessage());
}
// 处理MethodArgumentNotValidException 处理参数异常
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseResult handleValidException(MethodArgumentNotValidException e) {
log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String, String> errorMap = new HashMap<>();
bindingResult.getFieldErrors().forEach(fieldError -> {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
});
return ResultUtils.failure(errorMap.toString());
}
}