Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 527

How to define custom exception printers using Janestreet Core?

$
0
0

By default, a Failure exception is printed as such:

# print_endline (Printexc.to_string (Failure "uh\noh"));;Failure("uh\noh")

For improved readability, we want to print the argument of Failure as is because we understand it should be human-readable. In the OCaml standard library, we would initialize an application with the following:

# Printexc.register_printer (function  | Failure s -> Some ("Failure: " ^ s)  | _ -> None);;

The new behavior of Printexc.to_string would be:

# print_endline (Printexc.to_string (Failure "uh\noh"));;Failure: uhoh

Great. Now if we use the core_kernel library, first we can see that printing an exception is slightly different but not better to a human reader:

#require "core_kernel";;# print_endline (Printexc.to_string (Failure "uh\noh"));;(Failure  "uh\         \noh")

Perhaps we can override this? Let's try.

# Printexc.register_printer (function  | Failure s -> Some ("Failure: " ^ s)  | _ -> None);;# print_endline (Printexc.to_string (Failure "uh\noh"));;Failure: uhoh

This works, but it's not using the printer that's part of Core_kernel. If we use it, we still get the same unreadable result:

# print_endline (Core_kernel.Exn.to_string (Failure "uh\noh"));;(Failure  "uh\         \noh")

And Core_kernel.Exn doesn't offer a register_printer function. So effectively, it looks like Core_kernel.Exn makes sure that we don't define custom exception printers. Is there another way or should we just not use Core_kernel.Exn then if we want to show human-readable error messages?

Edit: For context, our original problem is to print nested error messages nicely. For example, we would like to read something like the following:

Uncaught exception: Failure:  Uncaught exception in subprocess 1234: Failure:    something happened    trace line 1    trace line 2  trace line 1  trace line 2  trace line 3

where we use indentation for quoting and escaping, rather than double-quotes and backslash escape sequences.


Viewing all articles
Browse latest Browse all 527

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>