c++仿照go语言的error,函数返回值封装
c++仿照go语言,程序返回错误时,可以附加错误信息
#ifndef __ERRORMSG_H_
#define __ERRORMSG_H_
#include <string>
struct Errormsg
{
typedef enum
{
OK = 0,
ERR = 1,
} HerrorCode;
HerrorCode code = OK;
std::string desc = "";
int line;
std::string file;
Errormsg() {}
Errormsg(HerrorCode c)
{
code = c;
}
Errormsg(HerrorCode c, const char *d)
{
code = c;
desc = d;
}
Errormsg(HerrorCode c, std::string d)
{
code = c;
desc = d;
}
Errormsg(HerrorCode c, std::string d, const char *_file, int _line)
{
code = c;
file = _file;
line = _line;
desc = d;
}
std::string flDesc()
{
return std::string("[") + file + "#" + std::to_string(line) + "]" + desc;
}
~Errormsg() {}
bool isOk() { return code == OK; }
};
#define ERRORSMSG_OK Errormsg(Errormsg::ERR, "ok")
#define ERRORSMSG_ERR(str) Errormsg(Errormsg::ERR, str)
#define ERRORSMSG_ERR_FL(str) Errormsg(Errormsg::ERR, str, __FILE__, __LINE__)
#endif
使用示例:
int main(int argc, char const *argv[])
{
Errormsg e = ERRORSMSG_OK;
printf("msg, %s\n", e.desc.c_str());
e = ERRORSMSG_ERR("run err");
printf("msg, %s\n", e.desc.c_str());
e = ERRORSMSG_ERR_FL("run err msg");
if (e.isOk()){
printf("run ok\n");
}
else{
printf("run err, file:%s, line:%d, msg: %s\n", e.file.c_str(), e.line, e.desc.c_str());
printf("run err, %s\n", e.flDesc().c_str());
}
return 0;
}
输出结果
msg, ok
msg, run err
run err, file:a.cpp, line:59, msg: run err msg
run err, [a.cpp#59]run err msg
更多编程资料见公众号 xutopia77