GCS  0.2.3
gu_throw.hpp
1 /*
2  * Copyright (C) 2009-2013 Codership Oy <info@codership.com>
3  *
4  * $Id: gu_throw.hpp 3515 2014-03-26 16:10:56Z yan $
5  */
6 
12 #ifndef __GU_THROW__
13 #define __GU_THROW__
14 
15 #include <cstring>
16 #include <cerrno>
17 #include <cstring>
18 #include <sstream>
19 
20 #include "gu_macros.h"
21 #include "gu_exception.hpp"
22 
23 namespace gu
24 {
26  class ThrowBase
27  {
28  protected:
29 
30  const char* const file;
31  const char* const func;
32  int const line;
33  std::ostringstream os;
34 
35  ThrowBase (const char* file_, const char* func_, int line_)
36  :
37  file (file_),
38  func (func_),
39  line (line_),
40  os ()
41  {}
42 
43  private:
44 
45  ThrowBase (const ThrowBase&);
46  ThrowBase& operator= (const ThrowBase&);
47 
48  friend class ThrowError;
49  friend class ThrowFatal;
50  };
51 
52  /* final*/ class ThrowError //: public ThrowBase
53  {
54  public:
55 
56  ThrowError (const char* file_,
57  const char* func_,
58  int line_,
59  int err_)
60  :
61  base (file_, func_, line_),
62  err (err_)
63  {}
64 
65  ~ThrowError() GU_NORETURN
66  {
67  base.os << ": " << err << " (" << ::strerror(err) << ')';
68 
69  Exception e(base.os.str(), err);
70 
71  e.trace (base.file, base.func, base.line);
72  // cppcheck-suppress exceptThrowInDestructor
73  throw e;
74  }
75 
76  std::ostringstream& msg () { return base.os; }
77 
78  private:
79 
80  ThrowBase base;
81  int const err;
82  };
83 
84  /* final*/ class ThrowFatal
85  {
86  public:
87 
88  ThrowFatal (const char* file, const char* func, int line)
89  :
90  base (file, func, line)
91  {}
92 
93  ~ThrowFatal () GU_NORETURN
94  {
95  base.os << " (FATAL)";
96 
97  Exception e(base.os.str(), ENOTRECOVERABLE);
98 
99  e.trace (base.file, base.func, base.line);
100  // cppcheck-suppress exceptThrowInDestructor
101  throw e;
102  }
103 
104  std::ostringstream& msg () { return base.os; }
105 
106  private:
107 
108  ThrowBase base;
109  };
110 }
111 
112 // Usage: gu_throw_xxxxx << msg1 << msg2 << msg3;
113 
114 #define gu_throw_error(err_) \
115  gu::ThrowError(__FILE__, __FUNCTION__, __LINE__, err_).msg()
116 
117 #define gu_throw_fatal \
118  gu::ThrowFatal(__FILE__, __FUNCTION__, __LINE__).msg()
119 
120 #endif // __GU_THROW__
Definition: gu_throw.hpp:52
Definition: gu_exception.hpp:19
Definition: gu_throw.hpp:84
Definition: gu_throw.hpp:26