Debian Codegraph @

src/mpt/exception/exception_text.hpp

raw
1 /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
2
3 #ifndef MPT_EXCEPTION_EXCEPTION_TEXT_HPP
4 #define MPT_EXCEPTION_EXCEPTION_TEXT_HPP
5
6
7
8 #include "mpt/base/namespace.hpp"
9 #include "mpt/exception/exception.hpp"
10 #include "mpt/string/types.hpp"
11 #include "mpt/string_transcode/transcode.hpp"
12
13 #include <exception>
14
15 #include <cstring>
16
17
18
19 namespace mpt {
20 inline namespace MPT_INLINE_NS {
21
22
23
24 template <typename Tstring>
25 inline Tstring get_exception_text(const std::exception & e) {
26 if (const mpt::exception_ustring_wrapper_base * pue = dynamic_cast<const mpt::exception_ustring_wrapper_base *>(&e)) {
27 const mpt::exception_ustring_wrapper_base & ue = *pue;
28 mpt::ustring what = ue.uwhat();
29 if (what.length() > 0) {
30 return mpt::transcode<Tstring>(std::move(what));
31 } else if (typeid(ue).name() && (std::strlen(typeid(ue).name()) > 0)) {
32 return mpt::transcode<Tstring>(mpt::source_string{typeid(ue).name()});
33 } else {
34 return mpt::transcode<Tstring>(mpt::source_string{"unknown exception name"});
35 }
36 } else if (e.what() && (std::strlen(e.what()) > 0)) {
37 return mpt::transcode<Tstring>(mpt::exception_string{e.what()});
38 } else if (typeid(e).name() && (std::strlen(typeid(e).name()) > 0)) {
39 return mpt::transcode<Tstring>(mpt::source_string{typeid(e).name()});
40 } else {
41 return mpt::transcode<Tstring>(mpt::source_string{"unknown exception name"});
42 }
43 }
44
45 template <>
46 inline std::string get_exception_text<std::string>(const std::exception & e) {
47 if (e.what() && (std::strlen(e.what()) > 0)) {
48 return std::string{e.what()};
49 } else if (typeid(e).name() && (std::strlen(typeid(e).name()) > 0)) {
50 return std::string{typeid(e).name()};
51 } else {
52 return std::string{"unknown exception name"};
53 }
54 }
55
56
57
58 template <typename Tstring>
59 inline Tstring get_current_exception_text() {
60 try {
61 throw;
62 } catch (const std::exception & e) {
63 return mpt::get_exception_text<Tstring>(e);
64 } catch (...) {
65 return mpt::transcode<Tstring>(mpt::source_string{"unknown exception"});
66 }
67 }
68
69 template <>
70 inline std::string get_current_exception_text<std::string>() {
71 try {
72 throw;
73 } catch (const std::exception & e) {
74 return mpt::get_exception_text<std::string>(e);
75 } catch (...) {
76 return std::string{"unknown exception"};
77 }
78 }
79
80
81
82 } // namespace MPT_INLINE_NS
83 } // namespace mpt
84
85
86
87 #endif // MPT_EXCEPTION_EXCEPTION_TEXT_HPP