bwidgets/inc/basic_widgets/core/error_helper.hpp

42 lines
1 KiB
C++
Raw Normal View History

#ifndef BWIDGETS_ERROR_HELPER_HPP
#define BWIDGETS_ERROR_HELPER_HPP
#include <functional>
2021-08-13 22:00:42 +02:00
#include <basic_widgets/core/type/sdl_error.hpp>
extern "C" {
auto SDL_GetError() -> const char*;
}
2021-08-13 22:00:42 +02:00
namespace bwidgets
{
template<Exception E, typename T>
inline auto ptr_or_throw(T* const ptr, const std::string_view w = "unknown") -> T*
2021-08-13 22:00:42 +02:00
{
std::string what;
2021-08-14 10:18:31 +02:00
if constexpr (std::is_same_v<E, SDLError>)
what = w == "unknown" ? SDL_GetError() : w;
2021-08-13 22:00:42 +02:00
else what = w;
if (ptr == nullptr) throw E(what);
return ptr;
}
template<Exception E, typename T>
inline auto success_or_throw(
const T code, const std::string_view w = "unknown",
const std::function<bool(T)>& success = [](T code) { return code == 0; }) -> T
2021-08-13 22:00:42 +02:00
{
if constexpr (std::is_same_v<E, SDLError>) {
const std::string what {w == "unknown" ? SDL_GetError() : w};
2021-08-14 10:18:31 +02:00
if (code < 0) throw E(what);
2021-08-13 22:00:42 +02:00
}
2021-08-14 16:43:25 +02:00
else if (success(code)) throw E(w);
2021-08-13 22:00:42 +02:00
return code;
}
}
#endif