Img2Num C++ (Internal Developer Docs)  dev
API Documentation
Error.h
1 #ifndef IMG2NUM_ERROR_H
2 #define IMG2NUM_ERROR_H
3 
4 #include <stdexcept>
5 #include <string>
6 
7 namespace img2num {
8 enum class Error { OK = 0, BAD_ALLOC = 1, INVALID_ARGUMENT = 2, RUNTIME = 3, UNKNOWN = 4 };
9 
10 extern thread_local Error last_error;
11 extern thread_local std::string last_error_message;
12 
13 inline Error get_last_error() {
14  return last_error;
15 }
16 inline const std::string get_last_error_message() {
17  return last_error_message;
18 }
19 void clear_last_error();
20 
21 void set_error(Error code, const std::string message);
22 
23 // Template function for catching and handling exceptions
24 template <typename Func, typename... Args>
25 void clear_last_error_and_catch(Func&& exception_prone_func, Args&&... args) {
26  clear_last_error(); // Clear any previous error state
27  try {
28  exception_prone_func(std::forward<Args>(args)...); // Call the passed function
29  } catch (const std::bad_alloc& e) {
30  set_error(Error::BAD_ALLOC, e.what());
31  } catch (const std::invalid_argument& e) {
32  set_error(Error::INVALID_ARGUMENT, e.what());
33  } catch (const std::runtime_error& e) {
34  set_error(Error::RUNTIME, e.what());
35  } catch (const std::exception& e) {
36  set_error(Error::UNKNOWN, e.what());
37  } catch (...) {
38  set_error(Error::UNKNOWN, "Unknown exception occurred");
39  }
40 }
41 } // namespace img2num
42 
43 #endif // IMG2NUM_ERROR_H
Definition: Error.h:7