项目地址:https://github.com/wlgq2/orca

orca中定义一套错误号码及提示信息以及断言,当程序发生错误时候,会输出错误信息或者终止程序。
在orca/base/error/ErrorInfo.h中可以到错误号码的定义如下:

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的错误处理函数如下:

    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文件中,代码如下:

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);
    }
};

通过相关宏定义使用,可以输出异常在代码中的发生位置:

#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)

莫失莫忘
9 声望1 粉丝