Img2Num C++
API Documentation
Loading...
Searching...
No Matches
Error.h
1#ifndef IMG2NUM_ERROR_H
2#define IMG2NUM_ERROR_H
3
4#include <stdexcept>
5#include <string>
6
7namespace img2num {
8enum class Error { OK = 0, BAD_ALLOC = 1, INVALID_ARGUMENT = 2, RUNTIME = 3, UNKNOWN = 4 };
9
10extern thread_local Error last_error;
11extern thread_local std::string last_error_message;
12
13inline Error get_last_error() {
14 return last_error;
15}
16inline const std::string get_last_error_message() {
17 return last_error_message;
18}
19void clear_last_error();
20
21void set_error(Error code, const std::string message);
22
23// Template function for catching and handling exceptions
24template <typename Func, typename... Args>
25void 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