Custom Errors in OCaml

Our example demonstrates how to create and use custom errors in OCaml. We’ll create a custom error type and use it in a function that may fail under certain conditions.

(* A custom error type *)
type arg_error = {
  arg: int;
  message: string;
}

(* Exception for our custom error *)
exception ArgError of arg_error

(* Function that may raise our custom error *)
let f arg =
  if arg = 42 then
    raise (ArgError { arg; message = "can't work with it" })
  else
    arg + 3

(* Main function *)
let () =
  try
    let _ = f 42 in
    print_endline "Function succeeded"
  with
  | ArgError e ->
      Printf.printf "%d - %s\n" e.arg e.message
  | _ ->
      print_endline "Unknown error occurred"

In this OCaml code:

  1. We define a custom error type arg_error with fields for the argument and an error message.

  2. We create an ArgError exception that carries our custom error type.

  3. The f function raises our custom exception when the input is 42, otherwise it returns the input plus 3.

  4. In the main function, we use a try-with block to handle exceptions. This is similar to try-catch in other languages.

  5. If an ArgError is caught, we print its details. For any other exception, we print a generic message.

To run this program, save it as custom_errors.ml and use the OCaml compiler:

$ ocamlc custom_errors.ml -o custom_errors
$ ./custom_errors
42 - can't work with it

This example shows how to create and use custom errors in OCaml. While OCaml doesn’t have an exact equivalent to Go’s errors.As, the pattern matching in the exception handling provides similar functionality, allowing you to match and destructure specific error types.