阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_16-异常处理-可预知异常处理-自定义异常类型和抛出类
在common工程创建捕获异常的类:CustomException
Runtime叫做运行异常。在代码中抛出的话 对我们的代码没有可侵入性
如果在代码上抛出
如果改成Exception 这时候就会有错误提示。
那就必须要在方法的上面抛出‘
要么不在方法上抛出,去捕获
指定resultCode使用构造方法来赋值
捕获到了错误代码。就需要一个get方法去取出这个错误代码。这样自定义 异常类型就定义好了。
public class CustomException extends RuntimeException { ResultCode resultCode; public CustomException(ResultCode resultCode){ this.resultCode=resultCode; } public ResultCode getResultCode() { return resultCode; } }
定义好了自定义异常类,这里我们就可以在Service内 这么去抛出异常
public CmsPageResult add(CmsPage cmsPage){ //校验页面名称、站点Id、页面WebPath的唯一性 CmsPage cmsPage1=cmsPageRepository.findByPageNameAndSiteIdAndPageWebPath(cmsPage.getPageName(),cmsPage.getSiteId(),cmsPage.getPageWebPath()); if(cmsPage1==null){ throw new CustomException(CommonCode.FAIL); } cmsPage.setPageId(null);//设置设置为null 让mongoDB自动去生成, cmsPageRepository.save(cmsPage); return new CmsPageResult(CommonCode.SUCCESS,cmsPage); //return new CmsPageResult(CommonCode.FAIL,null); }
再专门定义一个异常抛出类
ExceptionCast
定义静态的方法,
public class ExceptionCast { public static void cast(ResultCode resultCode){ throw new CustomException(resultCode); } }
这样抛出异常。这种写法 就方便很多,
if(cmsPage1==null){
//throw new CustomException(CommonCode.FAIL);
ExceptionCast.cast(CommonCode.FAIL);
}
异常捕获类
抛出异常就需要有地方去捕获、定义异常捕获类:ExceptionCatch
使用@ControllerAdvice。
使用@ExceptionHandler捕获CustomException.class这个类的类型的异常。然后就可以获取到这个异常,并返回ReponseResult
@ControllerAdvice public class ExceptionCatch { //捕获CustomException此类异常 @ExceptionHandler(CustomException.class) public ResponseResult customException(CustomException customException){ ResultCode resultCode=customException.getResultCode(); return new ResponseResult(resultCode); } }
增加日志
注意Logger这个类是org.slf4j这个命名空间下的
完整代码
@ControllerAdvice
public class ExceptionCatch {
private static final Logger LOGGER= LoggerFactory.getLogger(ExceptionCatch.class);
//捕获CustomException此类异常
@ExceptionHandler(CustomException.class)
public ResponseResult customException(CustomException customException){
//获取异常信息,日志记录异常
LOGGER.error("catch exception:{}",customException.getMessage());
ResultCode resultCode=customException.getResultCode();
return new ResponseResult(resultCode);
}
}
public class CustomException extends RuntimeException {
ResultCode resultCode;
public CustomException(ResultCode resultCode){
this.resultCode=resultCode;
}
public ResultCode getResultCode() {
return resultCode;
}
}
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 7 个最近很火的开源项目「GitHub 热点速览」
· DeepSeekV3:写代码很强了
· 记一次 .NET某固高运动卡测试 卡慢分析
· Visual Studio 2022 v17.13新版发布:强化稳定性和安全,助力 .NET 开发提
· MySQL下200GB大表备份,利用传输表空间解决停服发版表备份问题