2021-08-19 15:00:44 +02:00
|
|
|
#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>
|
|
|
|
|
2021-08-19 15:00:44 +02:00
|
|
|
extern "C" {
|
|
|
|
auto SDL_GetError() -> const char*;
|
|
|
|
}
|
|
|
|
|
2021-08-13 22:00:42 +02:00
|
|
|
namespace bwidgets
|
|
|
|
{
|
|
|
|
template<Exception E, typename T>
|
2021-08-21 20:59:39 +02:00
|
|
|
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>
|
2021-08-14 09:17:51 +02:00
|
|
|
inline auto success_or_throw(
|
2021-08-21 20:59:39 +02:00
|
|
|
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>) {
|
2021-08-21 20:59:39 +02:00
|
|
|
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
|