Skip to content

Instantly share code, notes, and snippets.

@RoyBellingan
Last active December 29, 2022 14:01
Show Gist options
  • Save RoyBellingan/e62e2d713a5ae130be5c1d6509351b7c to your computer and use it in GitHub Desktop.
Save RoyBellingan/e62e2d713a5ae130be5c1d6509351b7c to your computer and use it in GitHub Desktop.
map for http get
#include <exception>
#include <fmt/format.h>
#include <map>
#include <source_location>
#include <string>
std::string locationFull(const std::source_location location = std::source_location::current()) {
return fmt::format("{}:{} in {}", location.file_name(), location.line(), location.function_name());
}
template <typename K>
class NotFoundMixin {
public:
using Funtor = void (*)(const K& key);
NotFoundMixin() = default;
NotFoundMixin(Funtor f)
: notFoundCallback(f){};
Funtor notFoundCallback = nullptr;
void callNotFoundCallback(const K& key, const std::string location) const {
(void)location;
if (notFoundCallback) {
(*notFoundCallback)(key);
return;
}
throw std::runtime_error(fmt::format("key >>>{}<<< not found in {}", key, location));
}
};
template <typename K, typename V, typename Compare = std::less<K>>
class mapV2 : public std::map<K, V, Compare>, public NotFoundMixin<K> {
public:
using value_type = std::pair<const K, V>;
using map_parent = std::map<K, V, Compare>;
using mixin_parent = NotFoundMixin<K>;
mapV2() = default;
mapV2(std::initializer_list<value_type> map_init)
: map_parent(map_init) {
}
mapV2(std::initializer_list<value_type> map_init, typename mixin_parent::Funtor f)
: map_parent(map_init), mixin_parent(f) {
}
[[nodiscard]] V rq(const K& k) const {
if (auto iter = this->find(k); iter != this->end()) {
return iter->second;
}
this->callNotFoundCallback(k, locationFull());
return {};
}
};
class HttpException : public std::exception {
public:
unsigned statusCode = 400;
// what to print to the user
std::string forceErrMsg;
static void HttpParamErrorHandler1(const std::string& key);
};
void HttpException::HttpParamErrorHandler1(const std::string& key) {
std::string msg = key + " is not set and is required!";
HttpException e;
e.forceErrMsg = msg;
e.statusCode = 200;
throw e;
}
int main() {
try {
mapV2<int, int> x{{1, 2}, {2, 3}};
x.rq(4);
} catch (...) {
}
try {
mapV2<std::string, int> getParameter({{"param1", 1}, {"param2", 2}}, HttpException::HttpParamErrorHandler1);
getParameter.rq("param3");
} catch (HttpException& e) {
//print on user
int y = 0;
} catch (std::exception& e) {
//print internally
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment