我已经不用 try catch 处理异常了!太辣鸡了!
浪尖聊大数据
共 20709字,需浏览 42分钟
· 2022-03-01
# 背景
# 什么是统一异常处理
# 目标
# 统一异常处理实战
用 Assert(断言) 替换 throw exception
@Test
public void test1() {
...
User user = userDao.selectById(userId);
Assert.notNull(user, "用户不存在.");
...
}
public void test2() {
// 另一种写法
User user = userDao.selectById(userId);
if (user == null) {
throw new IllegalArgumentException("用户不存在.");
}
}
public abstract class Assert {
public Assert() {
}
public static void notNull(@Nullable Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
}
Assert
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);
}
}
}
善解人意的Enum
public interface IResponseEnum {
int getCode();
String getMessage();
}
/**
*
业务异常
*
业务处理时,出现异常,可以抛出该异常
*/
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);
}
}
public interface BusinessExceptionAssert extends IResponseEnum, Assert {
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
}
@Getter
@AllArgsConstructor
public enum ResponseEnum implements BusinessExceptionAssert {
/**
* Bad licence type
*/
BAD_LICENCE_TYPE(7001, "Bad licence type."),
/**
* Licence not found
*/
LICENCE_NOT_FOUND(7002, "Licence not found.")
;
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
}
/**
* 校验{@link Licence}存在
* @param licence
*/
private void checkNotNull(Licence licence) {
ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
}
private void checkNotNull(Licence licence) {
if (licence == null) {
throw new LicenceNotFoundException();
// 或者这样
throw new BusinessException(7001, "Bad licence type.");
}
}
注:上面举的例子是针对特定的业务,而有部分异常情况是通用的,比如:服务器繁忙、网络异常、服务器异常、参数校验异常、404等,所以有CommonResponseEnum、ArgumentResponseEnum、ServletResponseEnum,其中 ServletResponseEnum 会在后文详细说明。
定义统一异常处理器类
4j
@Component
@ControllerAdvice
@ConditionalOnWebApplication
(UnifiedExceptionHandler.class)
public class UnifiedExceptionHandler {
/**
* 生产环境
*/
private final static String ENV_PROD = "prod";
private UnifiedMessageSource unifiedMessageSource;
/**
* 当前环境
*/
"${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 异常结果
*/
(value = BusinessException.class)
public ErrorResponse handleBusinessException(BaseException e) {
log.error(e.getMessage(), e);
return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
}
/**
* 自定义异常
*
* @param e 异常
* @return 异常结果
*/
(value = BaseException.class)
public ErrorResponse handleBaseException(BaseException e) {
log.error(e.getMessage(), e);
return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
}
/**
* Controller上一层相关异常
*
* @param e 异常
* @return 异常结果
*/
({
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
})
public ErrorResponse 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 new ErrorResponse(code, message);
}
return new ErrorResponse(code, e.getMessage());
}
/**
* 参数绑定异常
*
* @param e 异常
* @return 异常结果
*/
(value = BindException.class)
public ErrorResponse handleBindException(BindException e) {
log.error("参数绑定校验异常", e);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 参数校验异常,将校验失败的所有异常组合成一条错误信息
*
* @param e 异常
* @return 异常结果
*/
(value = MethodArgumentNotValidException.class)
public ErrorResponse handleValidException(MethodArgumentNotValidException e) {
log.error("参数绑定校验异常", e);
return wrapperBindingResult(e.getBindingResult());
}
/**
* 包装绑定异常结果
*
* @param bindingResult 绑定结果
* @return 异常结果
*/
private ErrorResponse 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));
}
/**
* 未定义异常
*
* @param e 异常
* @return 异常结果
*/
(value = Exception.class)
public ErrorResponse 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 new ErrorResponse(code, message);
}
return new ErrorResponse(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage());
}
}
进入Controller前的异常: handleServletException、handleBindException、handleValidException 自定义异常: handleBusinessException、handleBaseException 未知异常: handleException
# 异常处理器说明
handleServletException
handleBindException
handleValidException
handleBusinessException、handleBaseException
handleException
注:上面的handleServletException、handleException 这两个处理器,返回的异常信息,不同环境返回的可能不一样,以为这些异常信息都是框架自带的异常信息,一般都是英文的,不太好直接展示给用户看,所以统一返回SERVER_ERROR代表的异常信息。
# 异于常人的404
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
# 统一返回结果
# 验证统一异常处理
# 主要代码
@Service
public class LicenceService extends ServiceImpl<LicenceMapper, Licence> {
private OrganizationClient organizationClient;
/**
* 查询{@link Licence} 详情
* @param licenceId
* @return
*/
public LicenceDTO queryDetail(Long licenceId) {
Licence licence = this.getById(licenceId);
checkNotNull(licence);
OrganizationDTO org = ClientUtil.execute(() -> organizationClient.getOrganization(licence.getOrganizationId()));
return toLicenceDTO(licence, org);
}
/**
* 分页获取
* @param licenceParam 分页查询参数
* @return
*/
public QueryData
getLicences(LicenceParam licenceParam) {String licenceType = licenceParam.getLicenceType();
LicenceTypeEnum licenceTypeEnum = LicenceTypeEnum.parseOfNullable(licenceType);
// 断言, 非空
ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum);
LambdaQueryWrapper
wrapper = new LambdaQueryWrapper<>(); wrapper.eq(Licence::getLicenceType, licenceType);
IPage
page = this.page(new QueryPage<>(licenceParam), wrapper); return new QueryData<>(page, this::toSimpleLicenceDTO);
}
/**
* 新增{@link Licence}
* @param request 请求体
* @return
*/
(rollbackFor = Throwable.class)
public LicenceAddRespData addLicence(LicenceAddRequest request) {
Licence licence = new Licence();
licence.setOrganizationId(request.getOrganizationId());
licence.setLicenceType(request.getLicenceType());
licence.setProductName(request.getProductName());
licence.setLicenceMax(request.getLicenceMax());
licence.setLicenceAllocated(request.getLicenceAllocated());
licence.setComment(request.getComment());
this.save(licence);
return new LicenceAddRespData(licence.getLicenceId());
}
/**
* entity -> simple dto
* @param licence {@link Licence} entity
* @return {@link SimpleLicenceDTO}
*/
private SimpleLicenceDTO toSimpleLicenceDTO(Licence licence) {
// 省略
}
/**
* entity -> dto
* @param licence {@link Licence} entity
* @param org {@link OrganizationDTO}
* @return {@link LicenceDTO}
*/
private LicenceDTO toLicenceDTO(Licence licence, OrganizationDTO org) {
// 省略
}
/**
* 校验{@link Licence}存在
* @param licence
*/
private void checkNotNull(Licence licence) {
ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
}
}
-- licence
INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
VALUES (1, 1, 'user','CustomerPro', 100,5);
INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
VALUES (2, 1, 'user','suitability-plus', 200,189);
INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
VALUES (3, 2, 'user','HR-PowerSuite', 100,4);
INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
VALUES (4, 2, 'core-prod','WildCat Application Gateway', 16,16);
-- organizations
INSERT INTO organization (id, name, contact_name, contact_email, contact_phone)
VALUES (1, 'customer-crm-co', 'Mark Balster', 'mark.balster@custcrmco.com', '823-555-1212');
INSERT INTO organization (id, name, contact_name, contact_email, contact_phone)
VALUES (2, 'HR-PowerSuite', 'Doug Drewry','doug.drewry@hr.com', '920-555-1212');
# 开始验证
捕获自定义异常
捕获未知异常
# 小结
# 扩展
# 总结
4j
public class GlobalExceptionHandler {
/**
* 没有登录
* @param request
* @param response
* @param e
* @return
*/
(NoLoginException.class)
public Object noLoginExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
{
log.error("[GlobalExceptionHandler][noLoginExceptionHandler] exception",e);
JsonResult jsonResult = new JsonResult();
jsonResult.setCode(JsonResultCode.NO_LOGIN);
jsonResult.setMessage("用户登录失效或者登录超时,请先登录");
return jsonResult;
}
/**
* 业务异常
* @param request
* @param response
* @param e
* @return
*/
(ServiceException.class)
public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
{
log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e);
JsonResult jsonResult = new JsonResult();
jsonResult.setCode(JsonResultCode.FAILURE);
jsonResult.setMessage("业务异常,请联系管理员");
return jsonResult;
}
/**
* 全局异常处理
* @param request
* @param response
* @param e
* @return
*/
(Exception.class)
public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
{
log.error("[GlobalExceptionHandler][exceptionHandler] exception",e);
JsonResult jsonResult = new JsonResult();
jsonResult.setCode(JsonResultCode.FAILURE);
jsonResult.setMessage("系统错误,请联系管理员");
return jsonResult;
}
}
评论
雷军辟谣了!不是高考状元,卡里也没有冰冷的 40 亿
架构师大咖
架构师大咖,打造有价值的架构师交流平台。分享架构师干货、教程、课程、资讯。架构师大咖,每日推送。
公众号该公众号已被封禁最近很火的雷军简历,听说落魄时卡里只有冰冷的 40
源码共读
0
警报炸锅了,FastJson 又立功了。。
往期热门文章:1、一个小公司的技术开发心酸事(已倒闭)2、JetBrains 如何看待自己的软件在中国被频繁破解?3、程序员因Bug被要求归还4万多年终奖,网友:不还!4、一套万能通用的异步处理方案5、微服务全做错了!谷歌提出新方法,成本直接降9倍!线上事故回顾前段时间新增一个特别简单的功能,晚上上
Java后端技术
1
只要状态对了,事儿也就顺了
卖鸡蛋思维,适合各行各业的套用思维没钱时,牢记卖鸡蛋思维。 请一定耐心看完,成就不一样的你自己。When there‘s no money,Remember the thought of selling eggs.卖鸡蛋思维强调的是商业和经济思维的重要性,从商和创业都应该具备这样的思
小Q聊产品
0
我用这10招,能减少了80%的BUG
将Python客栈设为“星标⭐”第一时间收到最新资讯前言对于大部分程序员来说,主要的工作时间是在开发和修复BUG。有可能修改了一个BUG,会导致几个新BUG的产生,不断循环。那么,有没有办法能够减少BUG,保证代码质量,提升工作效率?答案是肯定的。如果能做到,我们多出来的时间,多摸点鱼,做点自己喜欢
Python客栈
0
请问哪位大佬有空?我自己搞不定pycharm安装调试了?
点击上方“Python共享之家”,进行关注回复“资源”即可获赠Python学习资料今日鸡汤残云归太华,疏雨过中条。大家好,我是Python进阶者。一、前言前几天在Python最强王者交流群【斌】问了一个Python环境安装的问题,请问哪位大佬有空?我自己搞不定pycharm安装调试了。二、实现过程这
IT共享之家
0
上门按摩的女技师们,要IPO了
不刮骨疗毒,怎么两袖清风?冲击万店,汉堡界能跑出下一个蜜雪冰城吗?拥有2.5万上门按摩女技师的东郊到家,要IPO了。消息源于东郊到家创始人汤帆在重庆首届O2O行业发展大会上的发言。汤帆表示,截至2023年底,东郊到家完成了部分IPO的规划实施及合规准备工作,并称东郊委托的上市中介机构是第一梯队的品牌
亿欧网
0
十万亿智慧养老市场,走到哪一步了?
《2024年智慧康养平台模式发展研究报告》即将发布。文|王菲当前,中国人口老龄化程度不断加剧,为了应对日益凸显的养老难题,构建多层次养老服务体系成为社会关注的热点。根据最新发布的《中华人民共和国2023年国民经济和社会发展统计公报》显示,我国60岁及以上的老年人口数量已达到2.97亿,占全国总人口的
亿欧网
0
3人运营,不用投流,年翻十倍...这些头部商家如何在得物获得确定性新增长
是新朋友吗?记得先点蓝字关注我哦~这场硬仗一定要打,也一定要打赢。文/靳舒乔珠宝品牌周大生2022年一季报数据显示,2021年周大生营收91.55亿元,门店突破4500家,遂加快线上渠道布局。一次跟得物官方交流,感觉这款App上的年轻人非常活跃,很契合线上发展需求。那时,得物App更名一年有余,正打
调皮电商
2