1.源码错误处理
常部分与异常部分,使代码的结构更加清晰
#define NGX_OK 0;
#define NGX_ERROR -1;
#define NGX AGAIN - 2 // 未准备好,需要重试
#define NGX BUSY - 3 //后端服务正忙
#define NGX DONE -4 //执行成功 ,但还需要有后续操作
#define NGX DECLINED -5 //执行成功 ,但未做处
#define NGX ABORT -6 //发生了严重 的错误
2.c++改造
2.1
public:
NgxException(ngx_int_t x, string_ref_type msg):
m_code(x), m_msg(msg)
{}
NgxException(ngx_int_t x = NGX_ERROR):
NgxException(x, "")
{}
NgxException(string_ref_type msg):
NgxException(NGX_ERROR, msg)
{}
virtual ~NgxException() noexcept
{}
ngx_int_t code() const
{
return m_code;
}
virtual const char* what() const noexcept override
{
return m_msg.c_str();
}
private:
ngx_int_t code=NGX_ERROR;
std::string m_msg;
1.设置成员 code(错误码) 以及错误信息
2.设置访问函数 来访问code
3.解析override
override保留字表示当前函数重写了基类的虚函数。
在函数比较多的情况下可以提示读者某个函数重写了基类虚函数,表示这个虚函数是从基类继承,不是派生类自己定义的;强制编译器检查某个函数是否重写基类虚函数,如果没有则报错。在类的成员函数参数列表后面添加该关键字既可。
表示这个函数是继承what();
4.初始化
1.已经有default构造
2.也设置赋值构造
3.委托构造
在c++11中有一个新特性,就是委托构造函数。委托构造函数可以使用当前类的其他构造函数来帮助当前构造函数初始化。换而言之,就是可以将当前构造函数的部分(或者全部)职责交给本类的另一个构造函数。
我们先看看委托构造函数与普通构造函数的相同点与不同点。
相同点: 两者都有一个成员初始值列表与一个函数体 不同点:
委托构造函数的成员初始值列表只有一个唯一的参数,就是构造函数(当然不能是当前的构造函数)
2.2
static void raise(ngx_int_t rc = NGX_ERROR, string_ref_type msg = "")
{
throw NgxException(rc, msg);
}
static void require(bool cond, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
if(!cond)
{
raise(e, msg);
}
}
static void require(ngx_int_t rc, ngx_int_t x = NGX_OK, string_ref_type msg = "")
{
require(rc == x, rc, msg);
}
template<typename T>
static void require(T* p, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
require(p != nullptr, e, msg);
}
static void fail(bool cond, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
if(cond)
{
raise(e, msg);
}
}
1. 异常的通常使用方式是直接用throw抛出,但这里我们把它封装为一个raise ( )函数,表现形式更好
2.检查错误码和空指针是 Nginx开发中经常要做的工作。反复出现的if语句很麻烦,由于异常处理流程与正常流程是分离的,所以可以轻松写出封装函数require( ) :
static void require(bool cond, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
if(!cond)
{
raise(e, msg);
}
}
static void require(ngx_int_t rc, ngx_int_t x = NGX_OK, string_ref_type msg = "")
{
require(rc == x, rc, msg);
}
template<typename T>
static void require(T* p, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
require(p != nullptr, e, msg);
}
3.有的时候当判断条件成立时的逻辑更容易书写,所以require()的“反函数”fail ()也很有用:
static void fail(bool cond, ngx_int_t e = NGX_ERROR, string_ref_type msg = "")
{
if(cond)
{
raise(e, msg);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/129639.html