f# - Overriding Exception.Message / exception pattern matching -
i'm trying pattern match on exception within definition. following possible using f#'s exception syntax, or must subclass exception?
this expected work:
exception coorderr of int * int override this.message = let coorderr(x, y) = sprintf "(%i %i)" x y //error but yields errors:
the value or constructor 'x' not defined
value or constructor 'y' not defined
edit
i tried adding parens:
let (coorderr(x, y)) = but gives error:
this expression expected have type exn here has type coorderr
update
the following works, isn't ideal:
exception coorderr of int * int override this.message = sprintf "(%i %i)" this.data0 this.data1 is there way this?
update 2
taking cue kvb's answer, suppose following swallow incomplete matches warning:
exception coorderr of int * int override this.message = match :> exn | coorderr(x, y) -> sprintf "(%i %i)" x y | _ -> unchecked.defaultof<_>
your first attempt doesn't work because you're defining let-bound function called coorderr shadows exception constructor, isn't want.
your second attempt works. unfortunately, exception definitions don't work quite discriminated unions: when pattern matching against exception constructor, expression you're matching has of type exn (and not of specific exception subtype). in case, trying match this (of type coorderr) against coorderr constructor. how's workaround?
exception coorderr of int * int override this.message = let (coorderr(x,y)) = upcast sprintf "(%i %i)" x y
Comments
Post a Comment