siplasplas
A library for C++ reflection and introspection
exception.hpp
1 #ifndef SIPLASPLAS_UTILITY_EXCEPTION_HPP
2 #define SIPLASPLAS_UTILITY_EXCEPTION_HPP
3 
4 #include "error_logger.hpp"
5 #include <ctti/type_id.hpp>
6 #include <stdexcept>
7 
8 namespace cpp
9 {
10 
37 template<typename Ex, typename Message>
38 void logException(const Message& message, std::size_t framesToSkip = 0)
39 {
40  cpp::utility::logErrorSkippingFrames(framesToSkip + 1, "'{}' exception thrown: {}", ctti::type_id<Ex>().name(), message);
41 }
42 
68 template<typename Ex>
69 void logException(const Ex& exception, std::size_t framesToSkip = 0)
70 {
71  logException<Ex>(exception.what(), framesToSkip + 1);
72 }
73 
84 template<typename Ex, typename Base = std::exception>
85 class Exception : public Base
86 {
87 public:
88  template<std::size_t N>
89  Exception(const char (&message)[N]) :
90  Base{message}
91  {
92  logException<Ex>(message);
93  }
94 
95  Exception(const std::string& message) :
96  Base{message}
97  {
98  logException<Ex>(message);
99  }
100 };
101 
136 template<typename Exception, typename... Args>
137 Exception exceptionSkippingFrames(std::size_t framesToSkip, const std::string& message, Args&&... args)
138 {
139  auto formattedMessage = fmt::format(message, std::forward<Args>(args)...);
140 
141  // siplasplas exceptions are logged automatically during construction
142  if(!std::is_base_of<::cpp::Exception<Exception>, Exception>::value)
143  {
144  // +1 to skip this frame too
145  logException<Exception>(formattedMessage, framesToSkip + 1);
146  }
147 
148  return Exception{formattedMessage};
149 }
150 
151 template<typename Exception, typename... Args>
185 Exception exception(const std::string& message, Args&&... args)
186 {
187  return exceptionSkippingFrames<Exception>(1, message, std::forward<Args>(args)...);
188 }
189 
193 template<typename Exception, typename... Args>
194 void Throw(const std::string& message, Args&&... args)
195 {
196  throw cpp::exceptionSkippingFrames<Exception>(1, message, std::forward<Args>(args)...);
197 }
198 
199 }
200 
201 #endif // SIPLASPLAS_UTILITY_EXCEPTION_HPP
Exception exception(const std::string &message, Args &&...args)
Instances an exception with a custom error message.
Definition: exception.hpp:185
Definition: canary_allocator.hpp:7
void logException(const Ex &exception, std::size_t framesToSkip=0)
Logs an exception.
Definition: exception.hpp:69
Exception exceptionSkippingFrames(std::size_t framesToSkip, const std::string &message, Args &&...args)
Instances an exception with a custom error message.
Definition: exception.hpp:137
void logErrorSkippingFrames(std::size_t framesToSkip, const Message &message, Args &&...args)
Log an error with its backtrace. Also skip the latest framesToSkip stack frames from stack trace...
Definition: error_logger.hpp:84
Declares a siplasplas exception type.
Definition: exception.hpp:85