PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/include/comet/error.h

https://bitbucket.org/alamaison/swish_comet
C Header | 429 lines | 286 code | 52 blank | 91 comment | 50 complexity | d5db7c29eb0ae9478b9da4af7bca1bb3 MD5 | raw file
  1. /** \file
  2. * Provide COM Error support.
  3. */
  4. /*
  5. * Copyright Š 2000, 2001 Sofus Mortensen
  6. *
  7. * This material is provided "as is", with absolutely no warranty
  8. * expressed or implied. Any use is at your own risk. Permission to
  9. * use or copy this software for any purpose is hereby granted without
  10. * fee, provided the above notices are retained on all copies.
  11. * Permission to modify the code and to distribute modified code is
  12. * granted, provided the above notices are retained, and a notice that
  13. * the code was modified is included with the above copyright notice.
  14. *
  15. * This header is part of comet.
  16. * http://www.lambdasoft.dk/comet
  17. */
  18. #ifndef COMET_ERROR_H
  19. #define COMET_ERROR_H
  20. #include <comet/config.h>
  21. #include <stdexcept>
  22. #include <string>
  23. #include <comet/error_fwd.h>
  24. #include <comet/bstr.h>
  25. #include <comet/ptr.h>
  26. #include <comet/uuid_fwd.h>
  27. #pragma warning(push)
  28. #pragma warning(disable : 4290)
  29. namespace comet {
  30. namespace impl {
  31. inline com_ptr<IErrorInfo> GetErrorInfo() throw()
  32. {
  33. IErrorInfo* ei = 0;
  34. ::GetErrorInfo(0, &ei);
  35. return com_ptr<IErrorInfo>(auto_attach(ei));
  36. }
  37. inline com_ptr<ICreateErrorInfo> CreateErrorInfo() throw()
  38. {
  39. ICreateErrorInfo* cei = 0;
  40. ::CreateErrorInfo(&cei);
  41. return com_ptr<ICreateErrorInfo>(auto_attach(cei));
  42. }
  43. template<typename Itf> inline bool supports_ErrorInfo(Itf* p)
  44. {
  45. com_ptr<ISupportErrorInfo> q = com_cast(com_ptr<Itf>(p));
  46. if (q == 0) return false;
  47. return S_OK == q->InterfaceSupportsErrorInfo(uuidof<Itf>());
  48. }
  49. }
  50. /** \class com_error error.h comet/error.h
  51. * COM error.
  52. */
  53. class com_error : public std::runtime_error
  54. {
  55. public:
  56. //! Construct com_error from HRESULT.
  57. /*!
  58. \param hr
  59. HRESULT value of error.
  60. */
  61. explicit com_error(HRESULT hr) : hr_(hr), std::runtime_error("")
  62. {}
  63. //! Construct com_error from HRESULT and textual description.
  64. /*!
  65. \param msg
  66. Description of error.
  67. \param hr
  68. HRESULT value of error.
  69. */
  70. explicit com_error(const bstr_t& msg, HRESULT hr = E_FAIL) : hr_(hr), std::runtime_error("")
  71. {
  72. com_ptr<ICreateErrorInfo> cei(impl::CreateErrorInfo());
  73. if ( !cei.is_null() ) {
  74. try {
  75. cei->SetDescription(msg.in());
  76. ei_ = com_ptr<IErrorInfo>( com_cast(cei)) ;
  77. } catch (std::bad_alloc&)
  78. {}
  79. }
  80. }
  81. //! Construct com_error from HRESULT, textual description, source, iid, help.
  82. /*!
  83. \param msg Description of error.
  84. \param hr HRESULT value of error.
  85. \param src Description of source line
  86. \param iid Interface the error was on
  87. \param helpFile Name of help file
  88. \param helpContext Name of help Context
  89. */
  90. explicit com_error(const bstr_t &msg, HRESULT hr, const bstr_t &src, const uuid_t &iid = uuid_t(),
  91. const bstr_t &helpFile=bstr_t(), DWORD helpContext = -1)
  92. : hr_(hr), std::runtime_error("")
  93. {
  94. com_ptr<ICreateErrorInfo> cei(impl::CreateErrorInfo());
  95. if ( ! cei.is_null() )
  96. {
  97. try {
  98. cei->SetDescription(msg.in());
  99. if (!src.is_null() )
  100. cei->SetSource( src.in() );
  101. if (iid != uuid_t())
  102. cei->SetGUID( iid );
  103. if (!helpFile.is_null())
  104. {
  105. cei->SetHelpFile( helpFile.in() );
  106. cei->SetHelpContext( helpContext );
  107. }
  108. ei_ = com_ptr<IErrorInfo>( com_cast(cei)) ;
  109. } catch (std::bad_alloc&)
  110. {}
  111. }
  112. }
  113. /// Construct with an error-info and hresult.
  114. explicit com_error(HRESULT hr, const com_ptr<IErrorInfo>& ei)
  115. : hr_(hr), ei_(ei), std::runtime_error("")
  116. {}
  117. public:
  118. //! Return a string with a description of the error
  119. /*!
  120. what() uses Description from IErrorInfo if such is present, otherwise FormatMessage is used
  121. to create a description of the HRESULT error value.
  122. \retval
  123. A const char* string with a textual description of the error.
  124. */
  125. const char* what() const throw()
  126. {
  127. try {
  128. if (what_.empty()) {
  129. what_ = s_str();
  130. }
  131. } catch (std::bad_alloc&) {
  132. return 0;
  133. }
  134. return what_.c_str();
  135. }
  136. /// Returns a std::string with a description of the error.
  137. std::string s_str() const
  138. {
  139. std::string ret;
  140. get_str(ret);
  141. return ret;
  142. }
  143. /// Returns a std::wstring with a description of the error.
  144. std::wstring w_str() const
  145. {
  146. std::wstring ret;
  147. get_str(ret);
  148. return ret;
  149. }
  150. /// Returns a tstring with a description of the error.
  151. tstring t_str() const
  152. {
  153. tstring ret;
  154. get_str(ret);
  155. return ret;
  156. }
  157. private:
  158. void get_str(std::string& ret) const
  159. {
  160. if (ei_.is_null() == false)
  161. {
  162. bstr_t bs;
  163. if (SUCCEEDED(ei_->GetDescription(bs.out())) && !bs.is_empty())
  164. {
  165. ret= bs.s_str();
  166. return;
  167. }
  168. }
  169. char* lpMsgBuf;
  170. if (FormatMessageA(
  171. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  172. FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr_,
  173. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  174. reinterpret_cast<char*>(&lpMsgBuf), 0, NULL))
  175. {
  176. char* lpEnd = lpMsgBuf;
  177. while (*lpEnd != '\0')
  178. lpEnd++;
  179. while (lpEnd > lpMsgBuf && // Trim trailing newlines
  180. (*(lpEnd - 1) == '\n' || *(lpEnd - 1) == '\r'))
  181. lpEnd--;
  182. ret.assign(lpMsgBuf, lpEnd - lpMsgBuf);
  183. LocalFree(lpMsgBuf);
  184. }
  185. }
  186. void get_str(std::wstring& ret) const
  187. {
  188. if (ei_.is_null() == false)
  189. {
  190. bstr_t bs;
  191. if (SUCCEEDED(ei_->GetDescription(bs.out())) && !bs.is_empty())
  192. {
  193. ret = bs.w_str();
  194. return;
  195. }
  196. }
  197. wchar_t* lpMsgBuf;
  198. if (FormatMessageW(
  199. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  200. FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr_,
  201. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  202. reinterpret_cast<wchar_t*>(&lpMsgBuf), 0, NULL))
  203. {
  204. wchar_t* lpEnd = lpMsgBuf;
  205. while (*lpEnd != L'\0')
  206. lpEnd++;
  207. while (lpEnd > lpMsgBuf && // Trim trailing newlines
  208. (*(lpEnd - 1) == L'\n' || *(lpEnd - 1) == L'\r'))
  209. lpEnd--;
  210. ret.assign(lpMsgBuf, lpEnd - lpMsgBuf);
  211. LocalFree(lpMsgBuf);
  212. }
  213. }
  214. public:
  215. /** Return the HRESULT for the error.
  216. */
  217. HRESULT hr() const throw()
  218. {
  219. return hr_;
  220. }
  221. /// \name wrappers for IErrorInfo
  222. //@{
  223. /// Description of the error.
  224. bstr_t description() const
  225. {
  226. bstr_t rv;
  227. if (!ei_.is_null()) ei_->GetDescription( rv.out() ) | raise_exception;
  228. return rv;
  229. }
  230. /// The error source description.
  231. bstr_t source() const
  232. {
  233. bstr_t rv;
  234. if (!ei_.is_null()) ei_->GetSource( rv.out() ) | raise_exception;
  235. return rv;
  236. }
  237. /// Interface IID.
  238. GUID guid() const
  239. {
  240. GUID rv;
  241. if (!ei_.is_null()) ei_->GetGUID( &rv ) | raise_exception;
  242. else ZeroMemory(&rv, sizeof(rv));
  243. return rv;
  244. }
  245. /// Helpfile name.
  246. bstr_t help_file() const
  247. {
  248. bstr_t rv;
  249. if (!ei_.is_null()) ei_->GetHelpFile( rv.out() ) | raise_exception;
  250. return rv;
  251. }
  252. /// Help conext.
  253. DWORD help_context() const
  254. {
  255. DWORD rv = 0;
  256. if (!ei_.is_null()) ei_->GetHelpContext( &rv ) | raise_exception;
  257. return rv;
  258. }
  259. //@}
  260. /// Return the error-info object.
  261. com_ptr<IErrorInfo> get_ei() const
  262. {
  263. return ei_;
  264. }
  265. private:
  266. mutable std::string what_;
  267. com_ptr<IErrorInfo> ei_;
  268. HRESULT hr_;
  269. };
  270. namespace impl {
  271. inline HRESULT return_com_error(HRESULT hr, const bstr_t &desc, const bstr_t &src = auto_attach(BSTR(NULL)),
  272. const uuid_t &iid=CLSID_NULL, const bstr_t &helpFile=bstr_t(), DWORD helpContext = -1)
  273. {
  274. com_ptr<ICreateErrorInfo> cei(impl::CreateErrorInfo());
  275. if (cei.is_null() == false) {
  276. try {
  277. cei->SetDescription(desc.in());
  278. if (!src.is_null() )
  279. cei->SetSource( src.in() );
  280. if (iid != uuid_t())
  281. cei->SetGUID( iid );
  282. if (!helpFile.is_null())
  283. {
  284. cei->SetHelpFile( helpFile.in() );
  285. cei->SetHelpContext( helpContext );
  286. }
  287. com_ptr<IErrorInfo> ei = com_cast(cei);
  288. ::SetErrorInfo(0, ei.in());
  289. } catch (std::bad_alloc&)
  290. {}
  291. }
  292. return hr;
  293. }
  294. inline HRESULT return_com_error(const std::exception& err, const bstr_t &src = auto_attach(BSTR(NULL)),
  295. const uuid_t &iid=CLSID_NULL, const bstr_t &helpFile=bstr_t(), DWORD helpContext = -1)
  296. {
  297. return return_com_error( E_FAIL, bstr_t(err.what()),src,iid,helpFile, helpContext );
  298. }
  299. inline HRESULT return_com_error(const com_error& err, const bstr_t &src = bstr_t(), const uuid_t &iid = CLSID_NULL) throw()
  300. {
  301. const bstr_t &cursrc =err.source();
  302. const uuid_t &curiid =err.guid();
  303. // Return error info with more info.
  304. return return_com_error( err.hr(), err.description(), cursrc.is_null()?src:cursrc,
  305. curiid.is_null()?iid:curiid, err.help_file(), err.help_context());
  306. }
  307. inline void throw_com_error_(HRESULT hr, const com_ptr<IErrorInfo>& ei)
  308. {
  309. throw_error_handler<true>::throw_error(hr, ei);
  310. }
  311. // Raising an HRESULT with a message
  312. inline void raise_exception_t::operator()(const bstr_t& msg, HRESULT hr/* = E_FAIL*/) const
  313. {
  314. throw com_error(msg, hr);
  315. }
  316. // Raising an HRESULT
  317. inline void raise_exception_t::operator()(HRESULT hr) const
  318. {
  319. throw com_error(hr);
  320. }
  321. } // namespace impl
  322. /*! \addtogroup ErrorHandling
  323. */
  324. //@{
  325. /** Throw COM error using com_error, using HRESULT and IErrorInfo.
  326. */
  327. template<typename Itf> inline void throw_com_error(Itf* p, HRESULT hr)
  328. {
  329. if (impl::supports_ErrorInfo(p))
  330. {
  331. com_ptr<IErrorInfo> ei = impl::GetErrorInfo();
  332. if (ei.is_null() == false) impl::throw_com_error_(hr, ei);
  333. }
  334. throw com_error(hr);
  335. }
  336. template<bool OVERRIDE>
  337. inline void throw_error_handler<OVERRIDE>::throw_error(HRESULT hr, const com_ptr<IErrorInfo> &ei)
  338. {
  339. throw com_error(hr, ei);
  340. }
  341. /**
  342. * Construct exception for a method called on a raw COM interface.
  343. *
  344. * This method aims to imbue the com_error with as much information about
  345. * the failure as possible:
  346. * - If the interface supports IErrorInfo, the information is taken from
  347. * the last ErrorInfo set on the current thread.
  348. * - If not, the HRESULT alone determines the message.
  349. *
  350. * Use this constructor immediately after an interface returns a
  351. * failure code before any other code can call SetErrorInfo and
  352. * overwrite the error.
  353. *
  354. * \param failure_source Interface whose method returned a failure code.
  355. * \param hr HRESULT value of error.
  356. *
  357. * \todo Can we add an optional user-defined message to this?
  358. */
  359. template<typename Itf>
  360. com_error com_error_from_interface(Itf* failure_source, HRESULT hr)
  361. {
  362. if (impl::supports_ErrorInfo(failure_source))
  363. return com_error(hr, impl::GetErrorInfo());
  364. else
  365. return com_error(hr);
  366. }
  367. template<typename Itf>
  368. com_error com_error_from_interface(
  369. com_ptr<Itf> failure_source, HRESULT hr)
  370. {
  371. return com_error_from_interface(failure_source.get(), hr);
  372. }
  373. //@}
  374. }
  375. #pragma warning(pop)
  376. #endif