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

I have a simple custom exception like the following, but I don’t like using the Throw function, and I really don’t like having the Throw and Throw2 functions. Is there a more elegant way to do this? Is there a way to throw MyError or Error directly without an intermediate function?

#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 use it as the following, but I would like to use one of the options that did not 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))) 
+4
source share
3 answers

Just ignore the exception construct and define the exception class, i.e. derived from System.Exception - directly, as in 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 the Msg element because exception already has the equivalent Message property.

+14
source

I'm not exactly what you are after, but how does it 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 
+1
source

How about overriding MyError as a record and using the syntax of the record to record the error, for example: -

 type MyError = { Msg: string; Code: int } exception Error of MyError raise <| Error { Msg = ( sprintf "Could not parse boolean value '%b'" key ); Code = code } 
+1
source

All Articles