F#中最常见的错误表示方式是什么 [英] What is the most idiomatic way of representing errors in F#

查看:69
本文介绍了F#中最常见的错误表示方式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究F#项目,我想知道使用F#中的 Result 类型返回域错误的最佳实践是什么?我认为有几种解决方法:

I'm working on F# project and I wonder what is the best practice to return domain error using Result type in F#. There are several ways of doing it which I consider:

继承的异常

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

那么哪种方法更惯用且方便使用?我也很高兴看到更好的选择。

So which way is more idiomatic and convenient to use? I also will be happy to see better options.

推荐答案

通常,这将是一个有区别的联合。每个错误都需要不同的详细信息来伴随消息。例如:

Typically it would be a discriminated union. Every error requires different details to accompany the message. For instance:

type DomainErrorTypes =
| ItemNotFound of ItemId
| FileNotFound of string
| InvalidFormat of format
| IncompatibleItems of Item * Item
| SQLError of code:int * message:string
| ...

您还可以捕获一些例外情况(不一定是全部):

You can also capture some exceptions (not necessarily all):

| ...
| Exception of exn

这篇关于F#中最常见的错误表示方式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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