Skip to content

Commit

Permalink
Implement wrapException to generalize parseConfigFileSimple
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Geod24 committed Jun 14, 2024
1 parent 58e19e6 commit 0a87067
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions source/configy/Read.d
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 0a87067

Please sign in to comment.