Skip to main content

Error.catch

catcherror_type handler

Group: Errors

Documentation

Executes the provided handler on an error, or returns the value unchanged.

Arguments

  • error_type: The type of error to handle. Defaults to Any to handle all errors.
  • handler: The function to call on this if it is an error value of a matching type. By default this is identity.

Examples

Catching an Illegal_Argument and returning its message.

      from Standard.Base import all

example_catch =
error = Error.throw (Illegal_Argument.Error "My message")
error.catch Illegal_Argument (err -> err.message)

Catching any dataflow error and turning it into a regular value.

      from Standard.Base import all

example_catch =
error = Error.throw 42
error.catch == 42

Catch a wrapped error in various ways.

      map_fun a = if a == 30 then Error.throw (Some_Error.Error a) else a+1

# Catch an error as the inner error
[10, 20, 30, 40] . map map_fun . catch Some_Error
# => (Some_Error.Error 30)

# Catch an error as the outer error
[10, 20, 30, 40] . map map_fun . catch Map_Error
# => (Map_Error.Error 2 (Some_Error.Error 30))

# Catch an error without specifying an error type
[10, 20, 30, 40] . map map_fun . catch
# => (Map_Error.Error 2 (Some_Error.Error 30))

Remarks

Wrapped Errors

A wrapped error is one that has been wrapped inside another error. For example, an error thrown in a Vector.map operation at index 3 would look like this:

(Map_Error.Error 3 (Some_Error.Error "an error occurred"))

A wrapped error can be caught either as as the inner error, or as the outer error, by using the error_type parameter. If it is caught as the inner error, the outer wrapping error is removed. If error_wrapper is unspecified or Any, the error is caught as the outer error.

A wrapping error must implement a conversion to Wrapped_Error to be treated properly as a wrapping error.