项目地址:https://github.com/wlgq2/orcaios
orca中定义一套错误号码及提示信息以及断言,当程序发生错误时候,会输出错误信息或者终止程序。
在orca/base/error/ErrorInfo.h中能够到错误号码的定义以下:git
namespace orca { namespace base { class ErrorInfo { public: enum ErrorId { UVWriteFail = -2048, UVConnectFail, UVDisconnectFromServer, UVSigPipe, UndefinedError = -1024, NoFindActorName, ActorNameTooLong, NoFindActorAddr, ReDefineActorName, MessagePackNull, PackMessageError, NoFindRemoteFramework, RepeatedRemoteFrameworkID, }; ErrorInfo(ErrorId id,std::string info); ErrorId getErrorId(); std::string& getErrorInfo(); private: ErrorId id_; std::string info_; }; } }
orca的错误处理函数以下:github
void error(ErrorInfo info) { if (handle_) handle_(info); else std::cerr << "error id "<< info.getErrorId() << ":" << info.getErrorInfo() << std::endl; }
若是用户没有自定义错误处理回调,orca只会cerr错误,不然会运行用户注册错误回调函数。
orca中经过RegisterErrorHandle接口来注册错误回调函数。
一个完整的例子:函数
#include <iostream> #include <orca/orca.h> REGISTER_MESSAGE_TYPE(std::string); void errorHandle(orca::base::ErrorInfo info) { std::cout << "error id : " << info.getErrorId() << std::endl; std::cout << "error message: " << info.getErrorInfo() << std::endl; } int main(int argc, char** args) { //actor framework. orca::Framework framework; framework.RegisterErrorHandle(std::bind(&errorHandle,std::placeholders::_1)); orca::base::ErrorHandle::Instance()->error(orca::base::ErrorInfo::UndefinedError,"undefine error"); framework.loop(); }
此外,orca简单的封装了断言用于打印信息并终止错误程序。在orca/core/Assert.h文件中,代码以下:oop
class Assert { public: static void IsFail(bool nomal, const char* const file, const unsigned int line, const std::string message = "") { if (!nomal) { Fail(file,line,message); } } static void Fail(const char* const file, const unsigned int line, const std::string message = "") { std::cerr<<"fail in :"<<file<<" at "<<line<<" lines."; if ("" != message) { std::cerr<<"\n:" << message; } std::cerr << "\n"; assert(false); } };
经过相关宏定义使用,能够输出异常在代码中的发生位置:spa
#define ORCA_FAIL() orca::Assert::Fail(__FILE__, __LINE__) #define ORCA_FAIL_MSG(msg) orca::Assert::Fail(__FILE__, __LINE__, msg) #define ORCA_ASSERT(condition) orca::Assert::IsFail(condition,__FILE__, __LINE__) #define ORCA_ASSERT_MSG(condition, msg) orca::Assert::IsFail(condition,__FILE__, __LINE__,msg)