From 0a87067b5c4190f1d2d0b7c866d0206350d31ecf Mon Sep 17 00:00:00 2001 From: Mathias Lang Date: Thu, 13 Jun 2024 21:35:12 +0200 Subject: [PATCH] Implement wrapException to generalize parseConfigFileSimple The need for parseConfigStringSimple recently arised in dub, and rather than implementing yet another function, we can generalize what parseConfigFileSimple is doing, allowing us to reuse the logic without introducing a new function. --- source/configy/Read.d | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/source/configy/Read.d b/source/configy/Read.d index ede142e..1c9b40b 100644 --- a/source/configy/Read.d +++ b/source/configy/Read.d @@ -287,18 +287,48 @@ public struct CLIArgs public Nullable!T parseConfigFileSimple (T) (string path, StrictMode strict = StrictMode.Error) { - return parseConfigFileSimple!(T)(CLIArgs(path), strict); + return wrapException(parseConfigFile!(T)(CLIArgs(path), strict)); } - /// Ditto -public Nullable!T parseConfigFileSimple (T) (in CLIArgs args, StrictMode strict = StrictMode.Error) +Nullable!T parseConfigFileSimple (T) (in CLIArgs args, StrictMode strict = StrictMode.Error) { - try + return wrapException(parseConfigFile!(args, strict)); +} + +/******************************************************************************* + + Wrap and print exceptions to stderr + + This allows to call either `parseConfigFile` or `parseConfigString` + and pretty-print the exception: + ``` + int main () { - Node root = Loader.fromFile(args.config_path).load(); - return nullable(parseConfig!T(args, root, strict)); + auto configN = wrapException( + parseConfigString!Config("config.yaml", "/dev/null") + ); + if (configN.isNull()) return 1; // Error path + auto config = configN.get(); + // Rest of the program ... } + ``` + + Params: + parseCall = A call to one of the `parse*` functions, such as + `parseConfigString` or `parseConfigFile`, or anything + that would call them. + + Returns: + An initialized `T` instance if reading/parsing was successful; + a `null` instance otherwise. + +*******************************************************************************/ + +public Nullable!T wrapException (T) (lazy T parseCall) +{ + try + return nullable(parseCall); catch (ConfigException exc) { exc.printException();