简体   繁体   English

F#:自定义例外。 有没有更好的方法来重载异常类型?

[英]F#: Custom exceptions. Is there a better way to overload the exception type?

I have a simple custom exception defined like like the following but I don't like having to use the Throw function and I really don't like having both Throw and a Throw2 functions. 我有一个简单的自定义异常,如下所示,但我不喜欢使用Throw函数,我真的不喜欢同时使用Throw和Throw2函数。 Is there a more elegant way of doing this? 有更优雅的方式吗? Is there a way of throwing MyError or Error directly without the intermediate function? 有没有一种方法可以在没有中间函数的情况下直接抛出MyError或Error?

#light

module Utilities.MyException

type MyError(code : int, msg : string) =
    member e.Msg  = msg
    member e.Code = code
    new (msg : string) = MyError(0, msg)

exception Error of MyError

let public Throw (msg : string) =
    let err = new MyError(msg)
    raise (Error err)

let public Throw2 (code : int) (msg : string) =
    let err = new MyError(code, msg)
    raise (Error err)

I'm using it like the following but I'd like to use one of the variants that didn't work 我正在使用它,如下所示,但我想使用其中一个不起作用的变体

Throw(System.String.Format("Could not parse boolean value '{0}'", key))

//The string isn't of the correct type for Error
//raise(Error(System.String.Format("Could not parse boolean value '{0}'", key)))

//MyError isn't compatible with System.Exception
//raise(MyError(System.String.Format("Could not parse boolean value '{0}'", key)))

Just ignore exception construct and define the exception class - that is, one deriving from System.Exception - directly, as in C#: 只需忽略exception构造并直接定义异常类 - 即从System.Exception派生的异常类,如在C#中:

type MyError(code : int, msg : string) =
    inherit Exception(msg)
    member e.Code = code
    new (msg : string) = MyError(0, msg)

raise(MyError("Foo"))
raise(MyError("Foo", 1))

Note that I removed Msg member, because Exception has an equivalent Message property already. 请注意,我删除了Msg成员,因为Exception已经具有等效的Message属性。

I am unclear exactly what you are after, but how does this work for you? 我不清楚你究竟是在追求什么,但这对你有什么用?

exception Error of int * string
let ErrorC(s) = Error(0,s)

let F() =
    try
        let key = true
        raise <| Error(42, System.String.Format("Could not parse '{0}'", key))
        raise <| ErrorC(System.String.Format("Could not parse '{0}'", key))
    with Error(code, msg) ->
        printfn "%d: %s" code msg

How about redefining MyError as a record and using the record syntax to record the error, eg:- 如何将MyError重新定义为记录并使用记录语法记录错误,例如: -

type MyError =
    { Msg:  string;
      Code: int } 

exception Error of MyError

raise <| Error { Msg  = ( sprintf "Could not parse boolean value '%b'" key );
                 Code = code }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM