bwidgets/inc/basic_widgets/core/error_helper.hpp

36 lines
966 B
C++

#ifndef BWIDGETS_ERROR_HELPER
#define BWIDGETS_ERROR_HELPER
#include <basic_widgets/core/type/exception.hpp>
#include <basic_widgets/core/type/sdl_error.hpp>
namespace bwidgets
{
template<Exception E, typename T>
static inline auto ptr_or_throw(T* ptr, const std::string& w = "") -> T*
{
std::string what;
if constexpr (std::is_same_v<E, SDLError>) what = w.empty() ? SDL_GetError() : w;
else what = w;
if (ptr == nullptr) throw E(what);
return ptr;
}
template<Exception E, typename T>
static inline auto success_or_throw(
T code, const std::string& w = "",
std::function<bool(T)> success = [](T code) { return code == 0; }) -> T
{
std::string what {w.empty() ? SDL_GetError() : w};
if constexpr (std::is_same_v<E, SDLError>) {
if (code <= 0) throw E(what);
}
else if (!success(code)) throw E(what);
return code;
}
}
#endif