Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Feature wish: custom exception printers #4477
Original bug ID: 4477
While we are at exceptions. It would be great if it were possible to define custom exception printers for the cases Printexc cannot handle automatically.
val register_printer : string -> (exn -> string) -> unit
This function is called with the name of the exception and the printing function. It is ensured by the runtime that the function is only called with the right exceptions, so a typical definition could be:
It is allowed to recursively call Printexc.to_string from within the printer.
I'm quite sure somebody will then come up with a camlp4 extension generating these definitions.
The motivation for this enhancement is that we are currently developing server components, and exceptions simply happen as part of normal operations. Usually they are handled by printing them to a log file, and then terminating the current action.
Currently, we work around by defining our own custom printers as normal O'Caml functions. But these work only for a specific context, e.g. we have Hydro_util.exn_to_string for all exceptions coming from Hydro (Wink's ICE implementation), and Pxp_types.string_of_exn for all exceptions coming from PXP, and a few other. Mixing these printers so they work for all relevant contexts is cumbersome.
Furthermore, we have the problem in server platforms like Hydro that we need to print exceptions that come from anywhere, e.g. because they are caught from an invocation of a user function. One can again work around by allowing to plug in custom printers, but this feels also a bit strange.
My thinking is that the O'Caml runtime is the right place for aggregating these functions.
Comment author: gerd
I've implemented this idea in ocamlnet, module Netexn:
The registry uses the name of the exception as key to a hash table (as an accelerator for lookups), and the reference to the exception definition block in an assoc list within that table. This block can be moved around by the GC, and cannot serve directly as hash key.
It is possible to define recursive printers for exception like
exception E of exn
but no provisions are taken for detecting cycles in the value graph.