bwidgets/inc/basic_widgets/core/error_helper.hpp

47 lines
1.4 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
{
2021-08-23 23:50:14 +02:00
// Throw a E exception with message w if ptr is null. Otherwise return ptr.
2021-08-13 22:00:42 +02:00
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;
}
2021-08-23 23:50:14 +02:00
// Check a return code with the success function passed. If success return false
// throw an E Exception with message w.
2021-08-13 22:00:42 +02:00
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
{
2021-08-23 23:50:14 +02:00
// If exception type is SDLError and no value or unknown was passed for w, get
// the last error message using SDL facilities.
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-24 00:00:28 +02:00
else if (!success(code)) throw E(w.data());
2021-08-13 22:00:42 +02:00
return code;
}
}
#endif