|
| 1 | +/*******************************************************************\ |
| 2 | +
|
| 3 | +Module: util |
| 4 | +
|
| 5 | +Author: Diffblue Ltd. |
| 6 | +
|
| 7 | +\*******************************************************************/ |
| 8 | + |
| 9 | +#include "unwrap_nested_exception.h" |
| 10 | +#include "invariant.h" |
| 11 | +#include "string_utils.h" |
| 12 | +#include "suffix.h" |
| 13 | + |
| 14 | +#include <sstream> |
| 15 | +#include <vector> |
| 16 | + |
| 17 | +/// Given a potentially nested exception, produce a string with all of nested |
| 18 | +/// exceptions information. If a nested exception string contains new lines |
| 19 | +/// then the newlines are indented to the correct level. |
| 20 | +/// \param e: The outer exeception |
| 21 | +/// \param level: How many exceptions have already been unrolled |
| 22 | +/// \return A string with all nested exceptions printed and indented |
| 23 | +std::string unwrap_exception(const std::exception &e, int level) |
| 24 | +{ |
| 25 | + const std::string msg = e.what(); |
| 26 | + std::vector<std::string> lines; |
| 27 | + split_string(msg, '\n', lines, false, true); |
| 28 | + std::ostringstream message_stream; |
| 29 | + message_stream << std::string(level, ' ') << "exception: "; |
| 30 | + join_strings( |
| 31 | + message_stream, lines.begin(), lines.end(), "\n" + std::string(level, ' ')); |
| 32 | + |
| 33 | + try |
| 34 | + { |
| 35 | + std::rethrow_if_nested(e); |
| 36 | + } |
| 37 | + catch(const std::exception &e) |
| 38 | + { |
| 39 | + std::string nested_message = unwrap_exception(e, level + 1); |
| 40 | + // Some exception messages already end in a new line (e.g. as they have |
| 41 | + // dumped an irept. Most do not so add a new line on. |
| 42 | + if(nested_message.back() != '\n') |
| 43 | + { |
| 44 | + message_stream << '\n'; |
| 45 | + } |
| 46 | + message_stream << nested_message; |
| 47 | + } |
| 48 | + catch(...) |
| 49 | + { |
| 50 | + UNREACHABLE; |
| 51 | + } |
| 52 | + return message_stream.str(); |
| 53 | +} |
0 commit comments