Error Handling with Core Guidelines GSL Expects, Ensures, and narrow_cast

1.1k Views Asked by At

I am trying to follow the Cpp Core Guidelines and use GSL where appropriate. In particular, I would like to use Expects and Ensures for pre and post-conditions, as well as span, and narrow_cast, but the error handling is not robust and does not provide any diagnostics. When encountering errors GSL simply calls terminate leaving the tester with no clues as to what caused the termination.

So my question is: How does one use GSL and keep code robust in the presence of errors? Or more simply, how to use GSL and get error diagnostics prior to termination?

1

There are 1 best solutions below

2
On

I don't see an easy way to achieve that. You could write your own terminate handler that gets called by std::terminate, but that has no context of where and why std::terminate was called. Depending on the platform it might be possible to get a backtrace and retrieve some information at least about the caller, but that is not of great help.

For MS/GSL I provided some code in a pull request that enriches the exception thrown by narrow_cast, but that PR was rejected because it pulls in the streaming library. Herb Sutter, part of the CppCoreGuidelines committee said:

C++ Core Guidelines editors' call: This seems to be asking for a debugging aid that can be expensive in release mode. It could be added in debug mode only, and then only for projects that are not supposed to change their dependencies between debug and release modes (which seems undesirable because it limits use of GSL in such projects). Better would be to use the debugger to view the information if an exception is thrown, such as by setting a breakpoint in the implementation of narrow.

My branch is deleted, but can be restored if you like to integrate that feature in your code.