Commit 10ba9c05 authored by 竹天卫's avatar 竹天卫

统一异常处理模块3

parent f110d894
package cn.wise.sc.acquisition.business.controller;
import cn.wise.im.common.http.R;
import cn.wise.sc.acquisition.business.model.PageQuery;
import cn.wise.sc.acquisition.business.service.ITEquipmentAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2021-04-23
*/
@Api(tags = "设备管理")
@RestController
@RequestMapping("/business/t-equipment-account")
public class TEquipmentAccountController {
@Autowired
private ITEquipmentAccountService equipmentAccountService;
@ApiOperation(value = "人员分页列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "EquipmentName", value = "设备名称", paramType = "query", dataType = "EquipmentName")
})
@GetMapping("/getPage")
public R getPage(PageQuery pageQuery, String EquipmentName) {
return equipmentAccountService.getPage(pageQuery, EquipmentName);
}
}
package cn.wise.sc.acquisition.business.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2021-04-23
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("T_Equipment_Account")
public class TEquipmentAccount implements Serializable {
private static final long serialVersionUID=1L;
/**
* 设备编码
*/
@TableId("EquipmentID")
private String EquipmentID;
/**
* 设备名称
*/
@TableField("EquipmentName")
private String EquipmentName;
/**
* 所属工序
*/
@TableField("ProcessesName")
private String ProcessesName;
/**
* 设备类型,包括租赁和自有
*/
@TableField("EquipmentType")
private String EquipmentType;
/**
* 机长
*/
@TableField("EquManager")
private String EquManager;
/**
* 规格型号
*/
@TableField("Ggxh")
private String Ggxh;
/**
* 生产能力
*/
@TableField("Scnl")
private String Scnl;
/**
* 装机容量
*/
@TableField("Zjrl")
private String Zjrl;
/**
* 生产厂家
*/
@TableField("Sccj")
private String Sccj;
/**
* 出厂日期
*/
@TableField("Ccrq")
private LocalDateTime Ccrq;
/**
* 出厂编号
*/
@TableField("Ccbh")
private String Ccbh;
/**
* 耐用年限
*/
@TableField("Nynx")
private String Nynx;
/**
* 资产编码
*/
@TableField("Zcbm")
private String Zcbm;
/**
* 设备原值
*/
@TableField("Yz")
private Float Yz;
/**
* 启用日期
*/
@TableField("Qyrq")
private LocalDateTime Qyrq;
/**
* 燃料类别
*/
@TableField("Rllb")
private String Rllb;
/**
* 转速
*/
@TableField("Zs")
private String Zs;
/**
* 状态,分为在用1和报废0
*/
@TableField("IsUsing")
private Boolean IsUsing;
/**
* 备注
*/
@TableField("Bz")
private String Bz;
}
package cn.wise.sc.acquisition.business.mapper;
import cn.wise.sc.acquisition.business.entity.TEquipmentAccount;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2021-04-23
*/
public interface TEquipmentAccountMapper extends BaseMapper<TEquipmentAccount> {
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.acquisition.business.mapper.TEquipmentAccountMapper">
</mapper>
package cn.wise.sc.acquisition.business.service;
import cn.wise.im.common.http.R;
import cn.wise.sc.acquisition.business.entity.TEquipmentAccount;
import cn.wise.sc.acquisition.business.model.PageQuery;
import cn.wise.sc.acquisition.business.model.query.TEquipmentAccountQuery;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2021-04-23
*/
public interface ITEquipmentAccountService extends IService<TEquipmentAccount> {
R<IPage<TEquipmentAccount>> getPage(PageQuery pageQuery, String EquipmentName);
R create(TEquipmentAccountQuery query);
R update(TEquipmentAccountQuery query);
R<TEquipmentAccount> getDetail(String EquipmentID);
R<List<TEquipmentAccount>> getList();
R<TEquipmentAccount> delete(String EquipmentID);
}
package cn.wise.sc.acquisition.business.service.impl;
import cn.wise.im.common.http.R;
import cn.wise.sc.acquisition.business.constant.Rcode;
import cn.wise.sc.acquisition.business.entity.TEquipmentAccount;
import cn.wise.sc.acquisition.business.mapper.TEquipmentAccountMapper;
import cn.wise.sc.acquisition.business.model.PageQuery;
import cn.wise.sc.acquisition.business.model.query.PostQuery;
import cn.wise.sc.acquisition.business.model.query.TEquipmentAccountQuery;
import cn.wise.sc.acquisition.business.service.ITEquipmentAccountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2021-04-23
*/
@Service
@Transactional
public class TEquipmentAccountServiceImpl extends ServiceImpl<TEquipmentAccountMapper, TEquipmentAccount> implements ITEquipmentAccountService {
@Resource
private TEquipmentAccountMapper equipmentAccountMapper;
/**
* 分页列表
* @param pageQuery
* @param EquipmentName
* @return
*/
@Override
public R<IPage<TEquipmentAccount>> getPage(PageQuery pageQuery, String EquipmentName) {
QueryWrapper<TEquipmentAccount> qw = new QueryWrapper<>();
if (StringUtils.isNotEmpty(EquipmentName)) {
qw.like("EquipmentName", EquipmentName);
}
qw.orderByDesc("Ccrq");
IPage<TEquipmentAccount> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
page = equipmentAccountMapper.selectPage(page, qw);
return R.ok(page);
}
/**
* 新增
* @param query
* @return
*/
@Override
public R create(TEquipmentAccountQuery query) {
Rcode.NOT_PARAM.assertNotNull(query);
Rcode.NOT_PARAM.assertNotNull(query.getEquipmentName());
TEquipmentAccount account = new TEquipmentAccount();
BeanUtils.copyProperties(query, account);
equipmentAccountMapper.insert(account);
return R.ok();
}
/**
* 修改
* @param query
* @return
*/
@Override
public R update(TEquipmentAccountQuery query) {
Rcode.NOT_PARAM.assertNotNull(query);
Rcode.NOT_PARAM.assertNotNull(query.getEquipmentID());
Rcode.NOT_PARAM.assertNotNull(query.getEquipmentName());
TEquipmentAccount account = equipmentAccountMapper.selectById(query.getEquipmentID());
Rcode.NOT_FOUND.assertNotNull(account);
BeanUtils.copyProperties(query, account);
equipmentAccountMapper.updateById(account);
return R.ok();
}
/**
* 详情
* @param EquipmentID
* @return
*/
@Override
public R<TEquipmentAccount> getDetail(String EquipmentID) {
Rcode.NOT_PARAM.assertNotNull(EquipmentID);
TEquipmentAccount account = equipmentAccountMapper.selectById(EquipmentID);
Rcode.NOT_FOUND.assertNotNull(account);
return R.ok(account);
}
/**
* 列表
* @return
*/
@Override
public R<List<TEquipmentAccount>> getList() {
List<TEquipmentAccount> list = this.list();
Rcode.NOT_FOUND.assertIsFalse(list!= null && list.size()>0);
return R.ok(list);
}
/**
* 删除
* @param EquipmentID
* @return
*/
@Override
public R<TEquipmentAccount> delete(String EquipmentID) {
Rcode.NOT_PARAM.assertNotNull(EquipmentID);
TEquipmentAccount account = equipmentAccountMapper.selectById(EquipmentID);
Rcode.NOT_FOUND.assertNotNull(account);
equipmentAccountMapper.deleteById(EquipmentID);
return R.ok();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>data-acquisition</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>im-common</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.wise.im.common.currency;
public interface IResponseEnum {
/**
* code
*获取返回码
* @return code
*/
int getCode();
/**
* message desc
*获取返回信息
* @return message
*/
String getMessage();
}
\ No newline at end of file
package cn.wise.im.common.currency.i18n;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Locale;
@Service
public class UnifiedMessageSource {
@Resource
private MessageSource messageSource;
/**
* 获取国际化消息
* @param code 消息code
* @return
*/
public String getMessage(String code) {
return getMessage(code, null);
}
/**
* 获取国际化消息
* @param code 消息code
* @param args 参数
* @return
*/
public String getMessage(String code, Object[] args) {
return getMessage(code, args, "");
}
/**
* 获取国际化消息
* @param code 消息code
* @param args 参数
* @param defaultMessage 默认消息
* @return
*/
public String getMessage(String code, Object[] args, String defaultMessage) {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(code, args, defaultMessage, locale);
}
}
\ No newline at end of file
package cn.wise.im.common.exception;
import cn.wise.im.common.currency.IResponseEnum;
/**
* <p>参数异常</p>
* <p>在处理业务过程中校验参数出现错误, 可以抛出该异常</p>
* <p>编写公共代码(如工具类)时,对传入参数检查不通过时,可以抛出该异常</p>
*/
public class ArgumentException extends BaseException {
private static final long serialVersionUID = 1L;
public ArgumentException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
public ArgumentException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
package cn.wise.im.common.exception;
import lombok.Getter;
import cn.wise.im.common.currency.IResponseEnum;
/**
* <p>基础异常类,所有自定义异常类都需要继承本类</p>
*/
@Getter
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 返回码
*/
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;
}
}
package cn.wise.im.common.exception;
import cn.wise.im.common.currency.IResponseEnum;
/**
* <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);
}
}
\ No newline at end of file
package cn.wise.im.common.exception;
import cn.wise.im.common.currency.IResponseEnum;
/**
* <p>校验异常</p>
* <p>调用接口时,参数格式不合法可以抛出该异常</p>
*/
public class ValidationException extends BaseException {
private static final long serialVersionUID = 1L;
public ValidationException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
public ValidationException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
package cn.wise.im.common.exception;
/**
* 只包装了 错误信息 的 {@link RuntimeException}.
* 用于中用于包装自定义异常信息
*/
public class WrapMessageException extends RuntimeException {
public WrapMessageException(String message) {
super(message);
}
public WrapMessageException(String message, Throwable cause) {
super(message, cause);
}
}
package cn.wise.im.common.exception.assertion;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.im.common.currency.IResponseEnum;
import cn.wise.im.common.exception.ArgumentException;
import cn.wise.im.common.exception.BaseException;
import java.text.MessageFormat;
/**
* <pre>
*参数异常断言
* </pre>
*/
public interface ArgumentExceptionAssert extends IResponseEnum, Assert {
@Override
default BaseException newException(Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new ArgumentException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new ArgumentException(this, args, msg, t);
}
}
package cn.wise.im.common.exception.assertion;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.im.common.exception.BaseException;
import cn.wise.im.common.exception.WrapMessageException;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Map;
import java.util.function.Supplier;
/**
* <p>枚举类异常断言,提供简便的方式判断条件,并在条件满足时抛出异常</p>
* <p>错误码和错误信息定义在枚举类中,在本断言方法中,传递错误信息需要的参数</p>
*/
public interface Assert {
/**
* 创建异常
*
* @param args
* @return
*/
BaseException newException(Object... args);
/**
* 创建异常
*
* @param t
* @param args
* @return
*/
BaseException newException(Throwable t, Object... args);
/**
* 创建异常.
* 先使用 {@code errMsg} 创建一个 {@link WrapMessageException} 异常,
* 再以入参的形式传给 {{{@link #newException(Throwable, Object...)}}}, 作为最后创建的异常的 cause 属性.
*
* @param errMsg 自定义的错误信息
* @param args
* @return
*/
default BaseException newExceptionWithMsg(String errMsg, Object... args) {
if (args != null && args.length > 0) {
errMsg = MessageFormat.format(errMsg, args);
}
WrapMessageException e = new WrapMessageException(errMsg);
throw newException(e, args);
}
/**
* 创建异常.
* 先使用 {@code errMsg} 和 {@code t} 创建一个 {@link WrapMessageException} 异常,
* 再以入参的形式传给 {{{@link #newException(Throwable, Object...)}}}, 作为最后创建的异常的 cause 属性.
*
* @param errMsg 自定义的错误信息
* @param args
* @return
*/
default BaseException newExceptionWithMsg(String errMsg, Throwable t, Object... args) {
if (ArrayUtil.isNotEmpty(args)) {
errMsg = MessageFormat.format(errMsg, args);
}
WrapMessageException e = new WrapMessageException(errMsg, t);
throw newException(e, args);
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
*
* @param obj 待判断对象
*/
default void assertNotNull(Object obj) {
if (obj == null) {
throw newException();
}
}
/**
* <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);
}
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertNotNullWithMsg(Object obj, String errMsg) {
if (obj == null) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotNullWithMsg(Object obj, String errMsg, Object... args) {
if (obj == null) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertNotNullWithMsg(Object obj, Supplier<String> errMsg) {
if (obj == null) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotNullWithMsg(Object obj, Supplier<String> errMsg, Object... args) {
if (obj == null) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言字符串<code>str</code>不为空串(长度为0)。如果字符串<code>str</code>为空串,则抛出异常
*
* @param str 待判断字符串
*/
default void assertNotEmpty(String str) {
if (null == str || "".equals(str.trim())) {
throw newException();
}
}
/**
* <p>断言字符串<code>str</code>不为空串(长度为0)。如果字符串<code>str</code>为空串,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param str 待判断字符串
* @param args message占位符对应的参数列表
*/
default void assertNotEmpty(String str, Object... args) {
if (str == null || "".equals(str.trim())) {
throw newException(args);
}
}
/**
* <p>断言字符串<code>str</code>不为空串(长度为0)。如果字符串<code>str</code>为空串,则抛出异常
*
* @param str 待判断字符串
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(String str, String errMsg) {
if (null == str || "".equals(str.trim())) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言字符串<code>str</code>不为空串(长度为0)。如果字符串<code>str</code>为空串,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param str 待判断字符串
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(String str, String errMsg, Object... args) {
if (str == null || "".equals(str.trim())) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
*
* @param arrays 待判断数组
*/
default void assertNotEmpty(Object[] arrays) {
if (arrays == null || arrays.length == 0) {
throw newException();
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param arrays 待判断数组
* @param args message占位符对应的参数列表
*/
default void assertNotEmpty(Object[] arrays, Object... args) {
if (arrays == null || arrays.length == 0) {
throw newException(args);
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
*
* @param arrays 待判断数组
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Object[] arrays, String errMsg) {
if (arrays == null || arrays.length == 0) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param arrays 待判断数组
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Object[] arrays, String errMsg, Object... args) {
if (arrays == null || arrays.length == 0) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
*
* @param arrays 待判断数组
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Object[] arrays, Supplier<String> errMsg) {
if (arrays == null || arrays.length == 0) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言数组<code>arrays</code>大小不为0。如果数组<code>arrays</code>大小不为0,则抛出异常
* <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param arrays 待判断数组
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Object[] arrays, Supplier<String> errMsg, Object... args) {
if (arrays == null || arrays.length == 0) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
*/
default void assertNotEmpty(Collection<?> c) {
if (c == null || c.isEmpty()) {
throw newException();
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
* @param args message占位符对应的参数列表
*/
default void assertNotEmpty(Collection<?> c, Object... args) {
if (c == null || c.isEmpty()) {
throw newException(args);
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Collection<?> c, String errMsg) {
if (c == null || c.isEmpty()) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Collection<?> c, String errMsg, Object... args) {
if (c == null || c.isEmpty()) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Collection<?> c, Supplier<String> errMsg) {
if (c == null || c.isEmpty()) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言集合<code>c</code>大小不为0。如果集合<code>c</code>大小不为0,则抛出异常
*
* @param c 待判断数组
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Collection<?> c, Supplier<String> errMsg, Object... args) {
if (c == null || c.isEmpty()) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
*/
default void assertNotEmpty(Map<?, ?> map) {
if (map == null || map.isEmpty()) {
throw newException();
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
* @param args message占位符对应的参数列表
*/
default void assertNotEmpty(Map<?, ?> map, Object... args) {
if (map == null || map.isEmpty()) {
throw newException(args);
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Map<?, ?> map, String errMsg) {
if (map == null || map.isEmpty()) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Map<?, ?> map, String errMsg, Object... args) {
if (map == null || map.isEmpty()) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
* @param errMsg 自定义的错误信息
*/
default void assertNotEmptyWithMsg(Map<?, ?> map, Supplier<String> errMsg) {
if (map == null || map.isEmpty()) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言Map<code>map</code>大小不为0。如果Map<code>map</code>大小不为0,则抛出异常
*
* @param map 待判断Map
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertNotEmptyWithMsg(Map<?, ?> map, Supplier<String> errMsg, Object... args) {
if (map == null || map.isEmpty()) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
*/
default void assertIsFalse(boolean expression) {
if (expression) {
throw newException();
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
* @param args message占位符对应的参数列表
*/
default void assertIsFalse(boolean expression, Object... args) {
if (expression) {
throw newException(args);
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息
*/
default void assertIsFalseWithMsg(boolean expression, String errMsg) {
if (expression) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsFalseWithMsg(boolean expression, String errMsg, Object... args) {
if (expression) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息
*/
default void assertIsFalseWithMsg(boolean expression, Supplier<String> errMsg) {
if (expression) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言布尔值<code>expression</code>为false。如果布尔值<code>expression</code>为true,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsFalseWithMsg(boolean expression, Supplier<String> errMsg, Object... args) {
if (expression) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
*/
default void assertIsTrue(boolean expression) {
if (!expression) {
throw newException();
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
* @param args message占位符对应的参数列表
*/
default void assertIsTrue(boolean expression, Object... args) {
if (!expression) {
throw newException(args);
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息
*/
default void assertIsTrueWithMsg(boolean expression, String errMsg) {
if (!expression) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsTrueWithMsg(boolean expression, String errMsg, Object... args) {
if (!expression) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息
*/
default void assertIsTrueWithMsg(boolean expression, Supplier<String> errMsg) {
if (!expression) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言布尔值<code>expression</code>为true。如果布尔值<code>expression</code>为false,则抛出异常
*
* @param expression 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsTrueWithMsg(boolean expression, Supplier<String> errMsg, Object... args) {
if (!expression) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断对象
*/
default void assertIsNull(Object obj) {
if (obj != null) {
throw newException();
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断布尔变量
* @param args message占位符对应的参数列表
*/
default void assertIsNull(Object obj, Object... args) {
if (obj != null) {
throw newException(args);
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertIsNullWithMsg(Object obj, String errMsg) {
if (obj != null) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsNullWithMsg(Object obj, String errMsg, Object... args) {
if (obj != null) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertIsNullWithMsg(Object obj, Supplier<String> errMsg) {
if (obj != null) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言对象<code>obj</code>为<code>null</code>。如果对象<code>obj</code>不为<code>null</code>,则抛出异常
*
* @param obj 待判断布尔变量
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertIsNullWithMsg(Object obj, Supplier<String> errMsg, Object... args) {
if (obj != null) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
*/
default void assertEquals(Object o1, Object o2) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newException();
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
* @param args message占位符对应的参数列表
*/
default void assertEquals(Object o1, Object o2, Object... args) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newException(args);
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertEqualsWithMsg(Object o1, Object o2, String errMsg) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newExceptionWithMsg(errMsg);
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertEqualsWithMsg(Object o1, Object o2, String errMsg, Object... args) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newExceptionWithMsg(errMsg, args);
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
* @param errMsg 自定义的错误信息
*/
default void assertEqualsWithMsg(Object o1, Object o2, Supplier<String> errMsg) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newExceptionWithMsg(errMsg.get());
}
}
/**
* <p>断言对象<code>o1</code>与对象<code>o2</code>相等,此处的相等指(o1.equals(o2)为true)。
* 如果两对象不相等,则抛出异常
*
* @param o1 待判断对象,若<code>o1</code>为null,也当作不相等处理
* @param o2 待判断对象
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertEqualsWithMsg(Object o1, Object o2, Supplier<String> errMsg, Object... args) {
if (o1 == o2) {
return;
}
if (o1 == null || !o1.equals(o2)) {
throw newExceptionWithMsg(errMsg.get(), args);
}
}
/**
* <p>直接抛出异常
*
*/
default void assertFail() {
throw newException();
}
/**
* <p>直接抛出异常
*
* @param args message占位符对应的参数列表
*/
default void assertFail(Object... args) {
throw newException(args);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param t 原始异常
*/
default void assertFail(Throwable t) {
throw newException(t);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param t 原始异常
* @param args message占位符对应的参数列表
*/
default void assertFail(Throwable t, Object... args) {
throw newException(t, args);
}
/**
* <p>直接抛出异常
*
* @param errMsg 自定义的错误信息
*/
default void assertFailWithMsg(String errMsg) {
throw newExceptionWithMsg(errMsg);
}
/**
* <p>直接抛出异常
*
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertFailWithMsg(String errMsg, Object... args) {
throw newExceptionWithMsg(errMsg, args);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param errMsg 自定义的错误信息
* @param t 原始异常
*/
default void assertFailWithMsg(String errMsg, Throwable t) {
throw newExceptionWithMsg(errMsg, t);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param t 原始异常
* @param args message占位符对应的参数列表
*/
default void assertFailWithMsg(String errMsg, Throwable t, Object... args) {
throw newExceptionWithMsg(errMsg, t, args);
}
/**
* <p>直接抛出异常
*
* @param errMsg 自定义的错误信息
*/
default void assertFailWithMsg(Supplier<String> errMsg) {
throw newExceptionWithMsg(errMsg.get());
}
/**
* <p>直接抛出异常
*
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param args message占位符对应的参数列表
*/
default void assertFailWithMsg(Supplier<String> errMsg, Object... args) {
throw newExceptionWithMsg(errMsg.get(), args);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param errMsg 自定义的错误信息
* @param t 原始异常
*/
default void assertFailWithMsg(Supplier<String> errMsg, Throwable t) {
throw newExceptionWithMsg(errMsg.get(), t);
}
/**
* <p>直接抛出异常,并包含原异常信息
* <p>当捕获非运行时异常(非继承{@link RuntimeException})时,并该异常进行业务描述时,
* 必须传递原始异常,作为新异常的cause
*
* @param errMsg 自定义的错误信息. 支持 {index} 形式的占位符, 比如: errMsg-用户[{0}]不存在, args-1001, 最后打印-用户[1001]不存在
* @param t 原始异常
* @param args message占位符对应的参数列表
*/
default void assertFailWithMsg(Supplier<String> errMsg, Throwable t, Object... args) {
throw newExceptionWithMsg(errMsg.get(), t, args);
}
}
package cn.wise.im.common.exception.assertion;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.im.common.currency.IResponseEnum;
import cn.wise.im.common.exception.BaseException;
import cn.wise.im.common.exception.BusinessException;
import java.text.MessageFormat;
/**
* <p>业务异常断言</p>
*/
public interface BusinessExceptionAssert extends IResponseEnum, Assert {
@Override
default BaseException newException(Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new BusinessException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new BusinessException(this, args, msg, t);
}
}
package cn.wise.im.common.exception.assertion;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.im.common.currency.IResponseEnum;
import cn.wise.im.common.exception.ArgumentException;
import cn.wise.im.common.exception.BaseException;
import java.text.MessageFormat;
/**
* <pre>
*通用异常断言
* </pre>
*/
public interface CommonExceptionAssert extends IResponseEnum, Assert {
@Override
default BaseException newException(Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new ArgumentException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = this.getMessage();
if (ArrayUtil.isNotEmpty(args)) {
msg = MessageFormat.format(this.getMessage(), args);
}
return new ArgumentException(this, args, msg, t);
}
}
package cn.wise.im.common.exception.enums;
import cn.wise.im.common.exception.assertion.CommonExceptionAssert;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>参数校验异常返回结果</p>
*/
@Getter
@AllArgsConstructor
public enum ArgumentResponseEnum implements CommonExceptionAssert {
/**
* 绑定参数校验异常
*/
VALID_ERROR(6000, "参数校验异常"),
;
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
}
package cn.wise.im.common.exception.enums;
import cn.wise.im.common.exception.BaseException;
import cn.wise.im.common.exception.assertion.CommonExceptionAssert;
import cn.wise.im.common.http.R;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>通用返回结果</p>
*/
@Getter
@AllArgsConstructor
public enum CommonResponseEnum implements CommonExceptionAssert {
/**
* 成功
*/
SUCCESS(0, "SUCCESS"),
/**
* 服务器繁忙,请稍后重试
*/
SERVER_BUSY(9998, "服务器繁忙"),
/**
* 服务器异常,无法识别的异常,尽可能对通过判断减少未定义异常抛出
*/
SERVER_ERROR(9999, "网络异常"),
/**
* 5***,一般对应于,系统封装的工具出现异常
*/
// Time
DATE_NOT_NULL(5001, "日期不能为空"),
DATETIME_NOT_NULL(5001, "时间不能为空"),
TIME_NOT_NULL(5001, "时间不能为空"),
DATE_PATTERN_MISMATCH(5002, "日期[%s]与格式[%s]不匹配,无法解析"),
PATTERN_NOT_NULL(5003, "日期格式不能为空"),
PATTERN_INVALID(5003, "日期格式[%s]无法识别"),
;
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
/**
* 校验返回结果是否成功
* @param response 远程调用的响应
*/
public static void assertSuccess(R response) {
SERVER_ERROR.assertNotNull(response);
int code = response.getCode();
if (CommonResponseEnum.SUCCESS.getCode() != code) {
String msg = response.getMessage();
throw new BaseException(code, msg);
}
}
}
package cn.wise.im.common.exception.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import javax.servlet.http.HttpServletResponse;
/**
* <p>异常类与http status对照关系</p>
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
*/
@Getter
@AllArgsConstructor
public enum ServletResponseEnum {
MethodArgumentNotValidException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
MethodArgumentTypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
MissingServletRequestPartException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
MissingPathVariableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
BindException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
MissingServletRequestParameterException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
TypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
ServletRequestBindingException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
HttpMessageNotReadableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
NoHandlerFoundException(4404, "", HttpServletResponse.SC_NOT_FOUND),
NoSuchRequestHandlingMethodException(4404, "", HttpServletResponse.SC_NOT_FOUND),
HttpRequestMethodNotSupportedException(4405, "", HttpServletResponse.SC_METHOD_NOT_ALLOWED),
HttpMediaTypeNotAcceptableException(4406, "", HttpServletResponse.SC_NOT_ACCEPTABLE),
HttpMediaTypeNotSupportedException(4415, "", HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
ConversionNotSupportedException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
HttpMessageNotWritableException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
AsyncRequestTimeoutException(4503, "", HttpServletResponse.SC_SERVICE_UNAVAILABLE)
;
/**
* 返回码,目前与{@link #statusCode}相同
*/
private int code;
/**
* 返回信息,直接读取异常的message
*/
private String message;
/**
* HTTP状态码
*/
private int statusCode;
}
package cn.wise.im.common.exception.handler;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class GlobalExceptionHandler {
public static final String ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest reqest,
HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
// 是否ajax请求
if (isAjax(reqest)) {
return null;//JSONResult.errorException(e.getMessage());
} else {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", reqest.getRequestURL());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
public static boolean isAjax(HttpServletRequest httpRequest){
return (httpRequest.getHeader("X-Requested-With") != null
&& "XMLHttpRequest"
.equals( httpRequest.getHeader("X-Requested-With")) );
}
}
\ No newline at end of file
package cn.wise.im.common.exception.handler;
import cn.wise.im.common.http.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@RestController
@RequestMapping("${server.error.path:/error}")
public class MainsiteErrorController implements ErrorController {
private final String ERROR_PATH ="/error";
/**
* 出现错误,跳转到如下映射中
* @return
*/
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping
public R handleError(HttpServletRequest request, HttpServletResponse response) {
int code = response.getStatus();
if (404 == code) {
return R.fail(404, "未找到资源");
} else if (403 == code) {
return R.fail(403, "没有访问权限");
} else if (401 == code) {
return R.fail(401, "登录过期");
} else {
return R.fail(500, "服务器错误");
}
}
}
\ No newline at end of file
package cn.wise.im.common.exception.handler;
import cn.hutool.json.JSON;
import cn.wise.im.common.currency.i18n.UnifiedMessageSource;
import cn.wise.im.common.exception.BaseException;
import cn.wise.im.common.exception.BusinessException;
import cn.wise.im.common.exception.enums.ArgumentResponseEnum;
import cn.wise.im.common.exception.enums.CommonResponseEnum;
import cn.wise.im.common.exception.enums.ServletResponseEnum;
import cn.wise.im.common.http.R;
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.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
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.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <p>全局异常处理器</p>
*/
@Slf4j
@Component
@ControllerAdvice
@ConditionalOnWebApplication
@ConditionalOnMissingBean(UnifiedExceptionHandler.class)
public class UnifiedExceptionHandler {
/**
* 生产环境
*/
private final static String ENV_PROD = "prod";
@Autowired
private UnifiedMessageSource unifiedMessageSource;
/**
* 当前环境
*/
@Value("${spring.profiles.active}")
private String profile;
/**
* 获取国际化消息
*
* @param e 异常
* @return
*/
public String getMessage(BaseException e) {
String code = "response." + e.getResponseEnum().toString();
String message = unifiedMessageSource.getMessage(code, e.getArgs());
if (message == null || message.isEmpty()) {
return e.getMessage();
}
return message;
}
/**
* 业务异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public R handleBusinessException(BaseException e) {
log.error(e.getMessage(), e);
return R.fail(e.getResponseEnum().getCode(), getMessage(e));
}
/**
* 自定义异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = BaseException.class)
@ResponseBody
public R handleBaseException(BaseException e) {
log.error(e.getMessage(), e);
return R.fail(e.getResponseEnum().getCode(), getMessage(e));
}
/**
* Controller上一层相关异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler({
NoHandlerFoundException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
// BindException.class,
// MethodArgumentNotValidException.class
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
MissingServletRequestPartException.class,
AsyncRequestTimeoutException.class
})
@ResponseBody
public R handleServletException(Exception e) {
log.error(e.getMessage(), e);
int code = CommonResponseEnum.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 = CommonResponseEnum.SERVER_ERROR.getCode();
BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
String message = getMessage(baseException);
return R.fail(code, message);
}
return R.fail(code, e.getMessage());
}
/**
* 参数绑定异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = BindException.class)
@ResponseBody
public R handleBindException(BindException e) {
log.error("参数绑定校验异常", e);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 参数校验(Valid)异常,将校验失败的所有异常组合成一条错误信息
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class )
@ResponseBody
public R handleValidException(MethodArgumentNotValidException e) {
log.error("参数绑定校验异常", e);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 参数校验(ConstraintViolationException)异常
* @param ex
* @return
*/
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseBody
public R ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List<String> msgList = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> cvl = iterator.next();
msgList.add(cvl.getMessage());
}
return R.fail(ArgumentResponseEnum.VALID_ERROR.getCode(), msgList.get(0));
}
/**
* 包装绑定异常结果
*
* @param bindingResult 绑定结果
* @return 异常结果
*/
private R 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 R.fail(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2));
}
/**
* 未定义异常
*
* @param e 异常
* @return 异常结果
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public R handleException(Exception e) {
log.error(e.getMessage(), e);
if (ENV_PROD.equals(profile)) {
// 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
int code = CommonResponseEnum.SERVER_ERROR.getCode();
BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
String message = getMessage(baseException);
return R.fail(code, message);
}
return R.fail(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage());
}
}
package cn.wise.im.common.http;
import lombok.Data;
import java.io.Serializable;
@Data
public class R<T> implements Serializable {
private Integer code;
private String message;
private T data;
private R() {
}
public static <T> R<T> ok() {
return createResult(ResponseEnum.SUCCESS.getCode(), null, null);
}
public static <T> R<T> ok(T data) {
return createResult(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMessage(), data);
}
public static <T> R<T> ok(String message) {
return createResult(ResponseEnum.SUCCESS.getCode(), message, null);
}
public static <T> R<T> ok(T data, String message) {
return createResult(ResponseEnum.SUCCESS.getCode(), message, data);
}
public static <T> R<T> fail() {
return createResult(ResponseEnum.FAIL.getCode(), ResponseEnum.FAIL.getMessage(), null);
}
public static <T> R<T> fail(ResponseEnum responseCode) {
return createResult(responseCode.getCode(), responseCode.getMessage(), null);
}
public static <T> R<T> fail(ResponseEnum responseCode, T data) {
return createResult(responseCode.getCode(), responseCode.getMessage(), data);
}
public static <T> R<T> fail(ResponseEnum responseCode, String message) {
return createResult(responseCode.getCode(),
String.format("%s %s", responseCode.getMessage(), message), null);
}
public static <T> R<T> fail(Integer code, String message) {
return createResult(code, message, null);
}
private static <T> R<T> createResult(Integer code, String message, T data) {
R<T> r = new R<>();
r.setCode(code);
r.setMessage(message);
r.setData(data);
return r;
}
}
package cn.wise.im.common.http;
import cn.wise.im.common.currency.IResponseEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ResponseEnum implements IResponseEnum {
/**
* 成功
*/
SUCCESS(200, "请求成功"),
/**
* 失败
*/
FAIL(400, "请求失败"),
/**
* 用户信息不存在
*/
USER_NOT_FOUND(10001, "用户信息不存在"),
;
/**
* code
*/
final int code;
/**
* message desc
*/
final String message;
}
\ No newline at end of file
/**
* @author neo.shu
* @since 2021/4/16 15:33
*/
package cn.wise.im.common;
\ No newline at end of file
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.wise.im.common.exception.handler.UnifiedExceptionHandler,\
cn.wise.im.common.currency.i18n.UnifiedMessageSource
spring:
mvc:
throw-exception-if-no-handler-found: true
resources:
add-mappings: false
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment