我已經看過許多使用Option(對於簡單值)或者[List [Error],T]來處理錯誤的scala代碼片斷。在scala中使用異常是一個糟糕的做法嗎?
這給地方像這樣的代碼
def createApplicationToken(accessToken: AccessToken): Either[List[Error], ApplicationToken] = {
// go to social info provider and fetch information
retrieveProviderInfo(accessToken).fold(
errors => Left(errors),
info => {
// try to find user using the info from the provider
// if it's not there, create user
User.findOrCreateFromProviderInfo(info).fold(
errors => Left(errors),
user => {
// try to create a fresh token and save it to the user
user.refreshApplicationToken.fold(
errors => Left(errors),
user => Right(user.token)
)
}
)
}
)
其產生的不那麼漂亮的代碼嵌套,迫使你處理故障的每一個步驟,同時也迫使你把所有的函數返回一個要麼[ ...]
所以我想知道,如果
異常的使用Scala中(或一般函數式編程)氣餒
有使用它們(關於不變性或代碼併發)
例外是某種方式與原則或衝突功能的編程
你能想到的一個更好的方式來編寫的任何缺點給出的例子
-
人們可以通過退出本功能避免嵌套離子一旦發現使用return語句的錯誤,但使用返回也不鼓勵在標量...
相關http://stackoverflow.com/questions/12886285/throwing-exceptions-in-scala-what-is-the-official-rule的鏈接 –
感謝... – opensas
平面圖,狗屎 –