On 12.08.22 23:05, Christian Köstlin wrote:
On 12.08.22 01:50, H. S. Teoh wrote:
...
 >
The OP's idea of wrapping throwing code with a function that tacks on
extra information is a good idea.  Perhaps the use of strings isn't
ideal, but in principle I like his idea of exceptions acquiring
higher-level information as it propagates up the call stack.

Thanks for the kind words ... I am still thinking how to put this
into a nicer API ... as it is in my current demo, its not much to type
out so I am happy with that. Actually having read the source of
ifThrown, its amazing how lazy makes wrapping easy!
One thing that can be done is to templateize the exception handler so
that only exceptions of a certain type are handled.
```d
auto contextWithException(T, E)(lazy scope T expression, Exception delegate(E) handler)
{
    Exception newException;
    try
    {
        return expression();
    }
    catch (E e)
    {
        newException = handler(e);
    }
    throw newException;
}
```

which would enable something like

```d
    return  s
        .readText
        .parseJSON
        .contextWithException((UTFException e) {
return new Exception("Cannot process UTF-8 in config file%s\n %s".format(s, e.msg), e);
        })
        .contextWithException((FileException e) {
return new Exception("Cannot process config file%s\n %s".format(s, e.msg), e);
        });
```

Not sure if that makes it any better though, as I have the feeling that
most exceptions need to be wrapped at least once on their way to the end
user.

kind regards,
Christian

Reply via email to