1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
| class Exception { public: Exception(const string &errmsg, int &id) : _errmsg(errmsg), _id(id) { } virtual string what() const { return _errmsg; }
protected: string _errmsg; int _id; };
class SqlException : public Exception { public: SqlException(const string &errmsg, int id, const string &sql) : Exception(errmsg, id), _sql(sql) { } virtual string what() const { string str = "SqlException :"; str += _errmsg; str+="->"; str += _sql; return str; }
private: string _sql; };
class CacheException : public Exception { public: CacheException(const string &errmsg, int id) : Exception(errmsg, id) { } virtual string what() const { string str = "CacheException :"; str += _errmsg; return str; } };
class HttpException : public Exception { public: HttpException(const string &errmsg, int id, const string &type) : Exception(errmsg, id), _type(type) { } virtual string what() const { string str = "HttpException "; str += _type; str += ":"; str += _errmsg; return str; }
private: string _type; };
void SQLMgr() { if (rand() % 9 == 0) { throw SqlException("权限不足", 100,"select * from name = 'zhansang'"); } }
void CacheMgr() { if (rand() % 3 == 0) { throw CacheException("权限不足", 100); } if (rand() % 5 == 0) { throw CacheException("数据不存在", 101); } SQLMgr(); }
void HttpServer() { if (rand() % 2 == 0) { throw HttpException("请求资源不在", 100, "get"); } if (rand() % 7 == 0) { throw HttpException("权限不足", 101, "post"); } throw "xxxxxx"; CacheMgr(); } #include <chrono> #include <thread> #include <unistd.h> void ServerStart() { while (1) { this_thread::sleep_for(chrono::seconds(1)); try { HttpServer(); }
catch (const Exception &e) {
std::cerr << e.what() << endl; } catch (...) { std::cerr << "unknown Exception" << endl; } } }
void demo3() { ServerStart(); }
|