异常抛出介绍及处理方式

1. AuboException 头文件

  • 异常处理接口定义在type_def.h中

  • type() 方法可以错误类型

  • code() 方法可以返回错误码

  • what() 方法可以返回错误信息

     enum error_type
        {
            parse_error = -32700,
            invalid_request = -32600,
            method_not_found = -32601,
            invalid_params = -32602,
            internal_error = -32603,
            server_error,
            invalid
        };
    
        class AuboException : public std::exception
        {
        public:
            AuboException(int code, const std::string &prefix,
                          const std::string &message) noexcept
                : code_(code), message_(prefix + "-" + message)
            {
            }
    
            AuboException(int code, const std::string &message) noexcept
                : code_(code), message_(message)
            {
            }
    
            error_type type() const
            {
                if (code_ >= -32603 && code_ <= -32600) {
                    return static_cast<error_type>(code_);
                } else if (code_ >= -32099 && code_ <= -32000) {
                    return server_error;
                } else if (code_ == -32700) {
                    return parse_error;
                }
                return invalid;
            }
    
            int code() const { return code_; }
            const char *what() const noexcept override { return message_.c_str(); }
    
        private:
            int code_;
            std::string message_;
        };
    

2. 处理方式

采用try{...}catch(){...}方式捕获异常,方式如下:

    try{
        ...//出现异常的代码
    }
    catch (const arcs::aubo_sdk::AuboException& e) {
        //打印异常信息
        std::cout << "An exception occurs: " << e.what() << std::endl; 
        //打印错误码
        std::cout << "Exception code: " << e.code() << std::endl;
        //打印异常类型
        std::cout << "Exception type: " << e.type() << std::endl;
    }

3. 示例

  • 例如,填写一个错误的IP,SDK就会抛出异常

    #include "aubo_sdk/rpc.h"
    
    using namespace arcs::common_interface;
    using namespace arcs::aubo_sdk;
    
    int main(int argc, char** argv)
    {
        auto rpc_cli = std::make_shared<RpcClient>();
        try {
            //填写一个错误的IP 000.000.000.000
            std::string ip_local = "000.000.000.000";
            rpc_cli->connect(ip_local, 30004);
            rpc_cli->login("aubo", "123456");
        }
        catch (const arcs::aubo_sdk::AuboException& e) {
            std::cout << "An exception occurs: " << e.what() << std::endl;
            std::cout << "Exception code: " << e.code() << std::endl;
            std::cout << "Exception type: " << e.type() << std::endl;
        }
    }
    
  • 运行结果

results matching ""

    No results matching ""