bwidgets/inc/basic_widgets/core/error_helper.hpp

47 lines
1.4 KiB
C++

#ifndef BWIDGETS_ERROR_HELPER_HPP
#define BWIDGETS_ERROR_HELPER_HPP
#include <functional>
#include <basic_widgets/core/type/sdl_error.hpp>
extern "C" {
auto SDL_GetError() -> const char*;
}
namespace bwidgets
{
// Throw a E exception with message w if ptr is null. Otherwise return ptr.
template<Exception E, typename T>
inline auto ptr_or_throw(T* const ptr, const std::string_view w = "unknown") -> T*
{
std::string what;
if constexpr (std::is_same_v<E, SDLError>)
what = w == "unknown" ? SDL_GetError() : w;
else what = w;
if (ptr == nullptr) throw E(what);
return ptr;
}
// Check a return code with the success function passed. If success return false
// throw an E Exception with message w.
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
{
// If exception type is SDLError and no value or unknown was passed for w, get
// the last error message using SDL facilities.
if constexpr (std::is_same_v<E, SDLError>) {
const std::string what {w == "unknown" ? SDL_GetError() : w};
if (code < 0) throw E(what);
}
else if (success(code)) throw E(w);
return code;
}
}
#endif