How to provide dynamic type to an exception?

How would one provide a dynamic type to an exception?

For example, something like this:

exception ServerError('a)

This results in an “Unbound type parameter” error.

In contrast, this is achievable in a type declaration like so:

type serverError<'a> = 'a

For reference, here are the current docs on exceptions.

1 Like

I don’t think it’s possible. All exceptions are of exn type which is an extendable variant. So I assume all you can do is adding new constructors.

AFAIK, it wouldn’t be type-safe to have polymorphic exceptions. Consider this hypothetical code:

exception ServerError('a)

let f = x =>
  switch x {
  | true => raise(ServerError(1))
  | false => raise(ServerError("foo"))
  }

try {
  f(bar)
} catch {
| ServerError(x) => x // what type is x?
}

You either need to have a different exception for each type of payload, or use a monomorphic variant inside it.

exception ServerErrorInt(int)
exception ServerErrorString(string)
// or
type stringOrInt = String(string) | Int(int)
exception ServerError(stringOrInt)
1 Like

That makes sense. Thank you both.