Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

exception

f#

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. Is there a more elegant way of doing this? Is there a way of throwing MyError or Error directly without the 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'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)))
like image 593
telesphore4 Avatar asked Jul 28 '09 21:07

telesphore4


1 Answers

Just ignore exception construct and define the exception class - that is, one deriving 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 Msg member, because Exception has an equivalent Message property already.

like image 91
Pavel Minaev Avatar answered Nov 15 '22 11:11

Pavel Minaev