From 85373e52935332683372e42ef162a4141f0bf37a Mon Sep 17 00:00:00 2001 From: Patrick Wuttke Date: Fri, 25 Oct 2024 09:41:26 +0200 Subject: [PATCH] Added header for converting HRESULTs to exceptions. --- source/mijin/util/winerr.hpp | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 source/mijin/util/winerr.hpp diff --git a/source/mijin/util/winerr.hpp b/source/mijin/util/winerr.hpp new file mode 100644 index 0000000..e4002e2 --- /dev/null +++ b/source/mijin/util/winerr.hpp @@ -0,0 +1,69 @@ + + +#pragma once + +#if !defined(MIJIN_UTIL_WINERR_HPP_INCLUDED) +#define MIJIN_UTIL_WINERR_HPP_INCLUDED 1 + +#include + +#include +#include "./winundef.hpp" + +#include "./exception.hpp" + +namespace mijin +{ + +// +// public types +// + +class HRException : public Exception +{ +private: + HRESULT hResult_; +public: + explicit inline HRException(HRESULT hResult); + inline HRException(std::string_view message, HRESULT hResult); +}; + +// +// public functions +// + +[[nodiscard]] +inline std::string getHResultMessage(HRESULT hResult) +{ + if (hResult == S_OK) + { + return "Success (0x0)"; + } + return std::format("Unknown error (0x{:x}", hResult); +} + +inline HRESULT ensureHR(HRESULT hResult, std::string_view message = {}) +{ + if (!SUCCEEDED(hResult)) + { + if (message.empty()) + { + throw HRException(hResult); + } + throw HRException(message, hResult); + } + return hResult; +} + +HRException::HRException(HRESULT hResult) : Exception(getHResultMessage(hResult)), hResult_(hResult) +{ + +} + +HRException::HRException(std::string_view message, HRESULT hResult) + : Exception(std::format("{} {}", message, getHResultMessage(hResult))), hResult_(hResult) +{ + +} +} +#endif // !defined(MIJIN_UTIL_WINERR_HPP_INCLUDED)