diff options
author | temomik <temomik44@gmail.com> | 2023-12-01 20:16:03 +0000 |
---|---|---|
committer | temomik <temomik44@gmail.com> | 2023-12-01 20:16:03 +0000 |
commit | 658f37f93d1a0c31c447adb3022cfd6cee4a1876 (patch) | |
tree | 66f31434af61a5b4dda9a3591d67fc528273b505 /src | |
parent | 782596206764e663b9b45401b447871f21ce62b2 (diff) |
Added ability to handle error codes from all Api requests
Diffstat (limited to 'src')
-rw-r--r-- | src/Api.cpp | 25 | ||||
-rw-r--r-- | src/TgException.cpp | 4 |
2 files changed, 20 insertions, 9 deletions
diff --git a/src/Api.cpp b/src/Api.cpp index f238a70..f3f8124 100644 --- a/src/Api.cpp +++ b/src/Api.cpp @@ -2513,19 +2513,28 @@ boost::property_tree::ptree Api::sendRequest(const std::string& method, const st { try { std::string serverResponse = _httpClient.makeRequest(url, args); + if (!serverResponse.compare(0, 6, "<html>")) { - throw TgException("tgbot-cpp library have got html page instead of json response. Maybe you entered wrong bot token."); + std::string message = "tgbot-cpp library have got html page instead of json response. Maybe you entered wrong bot token."; + throw TgException(message, TgException::ErrorCode::HtmlResponse); } - boost::property_tree::ptree result = _tgTypeParser.parseJson(serverResponse); + boost::property_tree::ptree result; try { - if (result.get<bool>("ok", false)) { - return result.get_child("result"); - } else { - throw TgException(result.get("description", "")); - } + result = _tgTypeParser.parseJson(serverResponse); } catch (boost::property_tree::ptree_error& e) { - throw TgException("tgbot-cpp library can't parse json response. " + std::string(e.what())); + std::string message = "tgbot-cpp library can't parse json response. " + std::string(e.what()); + + throw TgException(message, TgException::ErrorCode::InvalidJson); + } + + if (result.get<bool>("ok", false)) { + return result.get_child("result"); + } else { + std::string message = result.get("description", ""); + size_t errorCode = result.get<size_t>("error_code", 0u); + + throw TgException(message, static_cast<TgException::ErrorCode>(errorCode)); } } catch (...) { int max_retries = _httpClient.getRequestMaxRetries(); diff --git a/src/TgException.cpp b/src/TgException.cpp index e61e09c..7164ddc 100644 --- a/src/TgException.cpp +++ b/src/TgException.cpp @@ -4,7 +4,9 @@ namespace TgBot { -TgBot::TgException::TgException(const std::string& description) : runtime_error(description) { +TgException::TgException(const std::string& description, ErrorCode errorCode) + : runtime_error(description), errorCode(errorCode) +{ } } |