-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_code_sample.cpp
More file actions
136 lines (119 loc) · 2.31 KB
/
error_code_sample.cpp
File metadata and controls
136 lines (119 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <iostream>
#include <system_error>
namespace Heresy
{
// define error code
enum class ErrorCode
{
Success = 0,
ErrorType1,
ErrorType2
};
// define error_category
class ErrorCategory : public std::error_category
{
public:
// map ErrorCode to detail message text
std::string message(int c) const override
{
switch (static_cast<ErrorCode>(c))
{
case ErrorCode::Success:
return "Success";
case ErrorCode::ErrorType1:
return "Error Type 1";
case ErrorCode::ErrorType2:
return "Error Type 2";
}
}
// the name of this error_category
const char* name() const noexcept override
{
return "Error Category by Heresy";
}
public:
// get referenceof shared ErrorCategory
static const std::error_category& get()
{
const static ErrorCategory sCategory;
return sCategory;
}
};
// convert ErrorCode to std::error_code
std::error_code make_error_code(ErrorCode ec)
{
return std::error_code(static_cast<int>(ec), ErrorCategory::get());
}
void MyFunction(bool bError);
void MyFunction(bool bError, std::error_code& ec);
std::error_code MyFunction2(bool bError);
}
namespace std
{
// let compiler know that Heresy::ErrorCode is compatible with std::error_code
template <>
struct is_error_code_enum<Heresy::ErrorCode> : true_type {};
}
int main()
{
// try-catch
{
try
{
Heresy::MyFunction(true);
}
catch (std::error_code & e)
{
std::cout << e.message() << std::endl;
}
}
// error_code as argument
{
std::error_code ec;
Heresy::MyFunction(true,ec);
if (ec)
{
std::cout << "Error : " << ec.message() << std::endl;
}
else
{
std::cout << "Work fine" << std::endl;
}
}
// error_code as retun value
{
std::error_code ec = Heresy::MyFunction2(true);
if (ec == Heresy::ErrorCode::ErrorType1)
{
// do something
std::cout << ec << std::endl;
}
else if (ec == Heresy::ErrorCode::ErrorType2)
{
// do something
}
}
return 0;
}
namespace Heresy
{
void MyFunction(bool bError)
{
if (bError)
throw make_error_code(ErrorCode::ErrorType1);
}
void MyFunction(bool bError, std::error_code& ec)
{
if (bError)
ec = ErrorCode::ErrorType2;
else
ec = ErrorCode::Success;
}
std::error_code MyFunction2(bool bError)
{
if (bError)
return ErrorCode::ErrorType1;
else
return ErrorCode::Success;
}
}