在Scala中返回Future.failed(new Exception(“”))时继续
发布时间:2020-12-16 19:18:35 所属栏目:安全 来源:网络整理
导读:如果未来返回失败的异常,我该如何处理? 场景是我的代码调用getValue(),将结果映射到verifyValue(),然后我希望能够处理getValue()的结果是Future.failed(new Exception(“message”))的情况.但是当我运行它时,如果getValue()的结果是失败的未来,它只会抛出异
如果未来返回失败的异常,我该如何处理?
场景是我的代码调用getValue(),将结果映射到verifyValue(),然后我希望能够处理getValue()的结果是Future.failed(new Exception(“message”))的情况.但是当我运行它时,如果getValue()的结果是失败的未来,它只会抛出异常而不是处理异常. 有没有人对我怎么做这个有什么建议? def method(): Future[JsObject] = { getValue().flatMap(verifyValue(_)) } def getValue(): Future[JsObject] = { try { value1 <- getValue1() value2 <- getValue2(value1) } yield { value2 } } def verifyValue(result: Any): Future[JsObject] = { result match { case e: Exception => getValue() case json: JsObject => Future.successful(json) } } 更新: 更新2: 解决方法
使用recover或recoverWith
当future将来因异常而失败时,将调用recover或recoverWith.在恢复块中,您可以提供替代值. recoverWith不同于恢复需要未来的东西 getValue().recover { case th => //based on the exception type do something here defaultValue //returning some default value on failure } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- SHELL训练营--day28_shell练习81-85
- WebService代码
- angularjs – Angular.js 1.3 ng-bind中的一次性绑定
- Bootstrap弹出框modal上层的输入框不能获得焦点问题的解决方
- Angular 5.0 学习8:Angular路由复用策略 (切换页面内容不丢
- 解决Scala中模糊的隐式转换
- 将Scala变量转换为Java对象… varargs
- 【layoutit!】基于 bootstrap 实现可视化布局工具
- twitter-bootstrap-3 – Bootstrap 3 – 集合箱宽度为940px
- 使用TypeScript的Angular2路由具有编译错误并获得意外的令牌