未来[Scala中的[AppError,Option [User]]] [英] Future[Either[AppError, Option[User]]] in Scala

查看:95
本文介绍了未来[Scala中的[AppError,Option [User]]]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题中提到的那样,使用这种数据结构有意义吗?让我一一解释:


  • 未来 - 表示异步计算

  • 已知错误

  • 选项 - 表明该值可能不存在



我是看这个时有点害怕。使用这种类型的组合是否是一种好的做法?

解决方案

让我们看一下解决方案空间:

 成功(Right(Some(user)))=> Everythig OK,得到用户
成功(Right(None))=>一切正常,没有用户
成功(Left(AppError))=>应用程序级别出错
失败(例外)=>出现错误

这看起来非常有表现力,但是当您尝试编写这样的嵌套结构时,事情会变得很难看与其他调用(请参阅将阻止代码转换为使用scala futures a>)作为构成 Future [Option [T]]



的示例。因此,最低权力原则
我们问自己:是否有较简单的替代方案可以保留语义?
如果我们充分利用异常(和异常层次结构)的潜力,可以说 Future [User] 就足够了。



让我们来检查一下:

  Everythig OK,got a user => ;成功(用户)
一切正常,没有用户=>失败(UserNotFoundException)(应用程序级别异常)
应用程序级别出错=>失败(AppException)(应用程序级别异常)
出错了=>失败(例外)(系统级异常)

这种方法的唯一限制是API将需要了解异常,这些异常在界面中并未自行记录。最重要的是,拥有基于 Future s的API将允许具有其他基于 Future 的API的表达一元组合。


As mentioned in the title, does it make sense to use such data structure? Let me explain one by one:

  • Future - to represent async computation
  • Either - to communicate known errors
  • Option - to communicate that the value may not be present

I am a little bit scared when looking at this. Is it a good practice to use such type combination?

解决方案

Let's have a look at the solution space:

Success(Right(Some(user))) => Everythig OK, got an user
Success(Right(None)) => Everything OK, no user
Success(Left(AppError)) => Something went wrong at app level
Failure(Exception) => Something went wrong

This looks very expressive, but things get ugly fast when you try to compose such nested structure with other calls (see Converting blocking code to using scala futures) for an example of composingFuture[Option[T]])

So following the principle of the least power, we ask ourselves: Are there less complex alternatives that preserve the semantics? One could argue that Future[User] could be sufficient if we make use of the full potential of exception (and exception hierarchies).

Let's check:

Everythig OK, got an user => Success(user)
Everything OK, no user => Failure(UserNotFoundException)  (Application level exception)
Something went wrong at app level => Failure(AppException) (Application level exception)
Something went wrong => Failure(Exception) (System-level exception)

The only limitation of this approach is that the users of the API will need to be aware of the Exceptions, which is not self-documented in the interface. The upper-hand is that having an API based on Futures will allow expressive monadic compositions with other Future-based APIs.

这篇关于未来[Scala中的[AppError,Option [User]]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆