异常 - 优雅处理

1.返回结果和异常如何选择
有数据需要回滚就抛出异常,否则返回结果
2.异常处理:
不是:
log.error("IO exception", e);
throw new MyException(e);
而是:
log.error("IO exception", "亨通接口出问题了,"+e.getMessage());
throw new MyException(1, "请求繁忙,请稍候再试!");

1.如何优雅处理异常
    1.1 为什么不建议用 try catch?:这篇文章不错,没有什么不建议使用try catch,而是应该如何在正确使用try catch:https://www.zhihu.com/question/29459586/answer/1910031749
    1.2 异常如何与断言结合处理,部分异常可使用断言替代,方便,简洁(spring使用断言和异常一同抛出异常,多学习)
    1.2.1 什么是断言:https://blog.csdn.net/qq_43567126/article/details/114776369
3.项目如何统一处理异常(待实践)
4.spring如何处理异常
例:XmlBeanDefinitionReader.class

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	Assert.notNull(encodedResource, "EncodedResource must not be null");
	if (logger.isTraceEnabled()) {
		logger.trace("Loading XML bean definitions from " + encodedResource);
	}

	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
	}

	try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
		InputSource inputSource = new InputSource(inputStream);
		if (encodedResource.getEncoding() != null) {
			inputSource.setEncoding(encodedResource.getEncoding());
		}
		return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				"IOException parsing XML document from " + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}
  1. 如何优雅处理异常、项目如何统一处理异常:https://zhuanlan.zhihu.com/p/68536207
  2. springmvc、springboot统一处理异常、统一返回结果https://blog.csdn.net/qq_42046105/article/details/123243661、https://blog.csdn.net/chinaherolts2008/article/details/120383594、https://zhuanlan.zhihu.com/p/28772817
  3. 统一返回数据的优化过程以及异常处理:SpringBoot 如何统一后端返回格式?老鸟们都是这样玩的! - 知乎


gateway也加入进来了统一结果返回:Spring Cloud 统一异常处理和统一返回 - 微笑不加冰 - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值