2016-10-26 92 views
1

我試圖根據FP範式轉換的以下功能:編寫功能代碼,例如查找功能

def findByEmail(email: String): User = { 
    val result = jdbc.find("select * from user where email..") 
    return result; 
} 

我第一次嘗試是下列之一:

def findByEmail(email: String): Either[String, Option[User]] = { 
    try { 
     val result = jdbc.find("select * from user where email..") 
    } catch (Exception e) { 
     return Left(e.getMessage()) 
    } 

    if (result == null) return Right(None) 

    Right(result) 
} 

事情我不喜歡是捕捉所有異常的嘗試。這種事情有沒有好的做法?左側是否有更好的數據類型而不是字符串?在那裏使用Exception類可以嗎?

+1

對於FP來說,這並不是真的。你應該幾乎不會捕獲所有的「異常」。 – Carcigenicate

+1

你的問題不清楚。你的第一個例子根本沒有發現異常,你的第二個例子就是這樣。你真的在問如何流動異常嗎? –

+0

你應該永遠不會捕獲所有的異常,但另一方面,異常會破壞RT並且不是類型安全的,所以我如何強制API的調用者來處理它們? – user3763116

回答

5

一種方法是改用Try[User]。然後,調用者可以匹配Success[A]Failure[Throwable]

def findByEmail(email: String): Try[User] = Try { jdbc.find("select * from user where email..") } 

然後就強制來電要麼提取從Try數據或構成它的方法:

findByEmail("[email protected]") match { 
    case Success(user) => // do stuff 
    case Failure(exception) => // handle exception 
} 

或者,如果你想撰寫方法:

// If the Try[User] is a Failure it will return it, otherwise executes the function. 
findByEmail("[email protected]").map { case user => // do stuff } 

另一種選擇是在@Reactormonk的評論中寫道是使用doobie這是一個有趣的通過JDBC爲Scala提供抽象層。