Error handling 用F表示错误最惯用的方法是什么#
我正在从事F#项目,我想知道使用Error handling 用F表示错误最惯用的方法是什么#,error-handling,f#,Error Handling,F#,我正在从事F#项目,我想知道使用Result输入F#返回域错误的最佳实践是什么。我认为有几种方法可以做到这一点: 继承的异常 type DomainException(message) = inherit Exception(message) type ItemNotFoundException(item) = inherit DomainException(sprintf "Item %s is not found" item) let findItem item =
Result
输入F#返回域错误的最佳实践是什么。我认为有几种方法可以做到这一点:
继承的异常
type DomainException(message) =
inherit Exception(message)
type ItemNotFoundException(item) =
inherit DomainException(sprintf "Item %s is not found" item)
let findItem item =
match item with
| Some x -> Ok x
| None -> Error(new ItemNotFoundException("someitem"))
自定义记录类型
type DomainError =
{ Name : string
Message : string }
let findItem item =
match item with
| Some x -> Ok x
| None ->
Error({ Name = "ItemNotFound"
Message = "Item someitem is not found" })
type DomainErrorTypes =
| ItemNotFoundError of DomainError
| ItemInvalidFormat of DomainError
let findItem item =
match item with
| Some x -> Ok x
| None ->
{ Name = "ItemNotFound"
Message = "Item someitem is not found" }
|> ItemNotFoundError
|> Error
记录类型的区分并集
type DomainError =
{ Name : string
Message : string }
let findItem item =
match item with
| Some x -> Ok x
| None ->
Error({ Name = "ItemNotFound"
Message = "Item someitem is not found" })
type DomainErrorTypes =
| ItemNotFoundError of DomainError
| ItemInvalidFormat of DomainError
let findItem item =
match item with
| Some x -> Ok x
| None ->
{ Name = "ItemNotFound"
Message = "Item someitem is not found" }
|> ItemNotFoundError
|> Error
那么,哪种方式更惯用、更方便使用呢?我也很乐意看到更好的选择。通常,这将是一个歧视性的联盟。每个错误都要求消息附带不同的详细信息。例如:
type DomainErrorTypes =
| ItemNotFound of ItemId
| FileNotFound of string
| InvalidFormat of format
| IncompatibleItems of Item * Item
| SQLError of code:int * message:string
| ...
您还可以捕获一些异常(不一定全部):
不过,我不会调用DU
DomainErrorTypes
,而只是调用DomainError
。(我知道这是OP的选择。)问题是我需要统一类型来表示不同类型的错误,以便能够在另一个服务中轻松解析它们。您可以使用函数将DU转换为统一类型DomainErrorTypes->string*string
这样您就可以充分利用这两个世界。通常,我们使用结果来传达作为工作流一部分的结果,无论是成功还是错误。异常处理程序通常用于处理意外错误,即不属于工作流一部分的错误,例如内存不足。有时,使用异常作为预期结果一部分的函数需要异常处理程序,您可以将这些异常处理程序封装在返回结果的函数中。