In a previous blog post, we discussed using an OCaml feature called polymorhpic variants for error handling. Here, let’s discuss some more advanced forms of this error-handling approach: returning multiple errors, performing error recovery, as well as handling warnings.
In many programs (for example, in a compiler or an IDE), we want to report all detected errors, instead of quitting on the first error. We also often want to collect warnings that are not critical for the execution of the program.
To demonstrate the problem and the solutions, let’s use an artificial example: a type checker for a small language with types t and terms e, which is technically a subset of OCaml:
It’s not a very useful language, but it is enough for us to discuss the interesting cases of error handling. We will represent this language with the following OCaml types:
As a recap, let’s first write the type checker while using exceptions for error handling. We start by defining failwithf which raises an exception like failwith, but allows printf-like formatting: