Scope
hresult_exception.h
1 #pragma once
2 
3 #include <atlexcept.h>
4 
7  : public std::exception {
8 
9 public:
11  HRESULT hr;
12 
14  char function[255];
15 
18  hresult_exception(const HRESULT& _hr = S_OK, const char _function[] = "none")
19  : hr(_hr) {
20  strcpy_s(function, 255, _function);
21  }
22 
24  const char *what() const {
25  return "HRESULT exception";
26  }
27 };
28 
30 template<bool ThrowException>
33  static bool Check(HRESULT _hr);
34 };
35 
37 template<> struct HResultChecker<false> {
39  static bool Check(const HRESULT& _hr) {
40  _hr;
41  return true;
42  }
43 };
44 
46 template<> struct HResultChecker<true> {
48  static bool Check(const HRESULT& _hr) {
49  if(FAILED(_hr)) {
50  throw std::exception("HResult exception");
51  return false;
52  }
53  return true;
54  }
55 };
56 
58 template<bool ThrowException>
59 class HResultT {
60 
61 protected:
63  HRESULT hr;
64 
66  char function[255];
67 
69  std::basic_string<WCHAR> desc;
70 
71 protected:
73  void Assign(const HRESULT& _hr) {
74  WORD code = HRESULT_CODE(_hr);
75  WORD facility = HRESULT_FACILITY(_hr);
76  DWORD severity = HRESULT_SEVERITY(_hr);
78  throw hresult_exception(hr, function);
79  }
80 
81 public:
83  HResultT(const HRESULT& _hr = S_OK, const char _function[] = "none")
84  : hr(_hr) {
85  strcpy_s(function, 255, _function);
86  Assign(hr);
87  }
88 
91  HResultT& operator() (const char _function[] = "none") {
92  strcpy_s(function, 255, _function);
93  return *this;
94  }
95 
96  HResultT& operator() (const HRESULT& _hr, const char _function[] = "none") {
97  strcpy_s(function, 255, _function);
98  Assign(_hr);
99  return *this;
100  }
101 
102  HResultT& operator= (const HRESULT& _hr) {
103  Assign(_hr);
104  return *this;
105  }
109  LPCTSTR ErrrorMessage() const {
110  return L"Error";
111  }
112 
114  operator HRESULT () const {
115  return hr;
116  }
117 };
118 
119 typedef HResultT<true> HResult;
120 
Exception class for HRESULTs.
static bool Check(HRESULT _hr)
Check.
std::basic_string< WCHAR > desc
more description
void Assign(const HRESULT &_hr)
Assign a HRESULT.
static bool Check(const HRESULT &_hr)
HRESULT hr
Current HRESULT.
LPCTSTR ErrrorMessage() const
Class around a HRESULT which breaks down the HRESULT code and makes life easier etc.
const char * what() const
HResultT(const HRESULT &_hr=S_OK, const char _function[]="none")
Constructor.
Templated helper class to check an HRESULT and throw an exception (or not throw)
HRESULT hr
HRESULT.
hresult_exception(const HRESULT &_hr=S_OK, const char _function[]="none")
static bool Check(const HRESULT &_hr)