|
- #pragma once
-
- #include "exception.h"
-
- namespace cppcore
- {
-
- /* exception */
-
- const exception::print_flags& exception::default_print_flag()
- {
- static const print_flags value({
- print_flag::print_trace,
- print_flag::resolve_address,
- });
- return value;
- }
-
- exception::exception()
- : exception("")
- { }
-
- exception::exception(std::string msg)
- : message (msg)
- , stack_size (0)
- , _msg_cache_empty (true)
- {
- stack_size = backtrace(&stack[0], max_stack_size);
- }
-
- void exception::print(std::ostream& os, const print_flags& flags) const
- {
- print_message(os);
- if (!flags.is_set(print_flag::print_trace))
- return;
- os << std::endl;
- char** lines = nullptr;
- if (flags.is_set(print_flag::resolve_address))
- lines = backtrace_symbols(stack, stack_size);
- for (int i = 0; i < stack_size; ++i)
- {
- os << " [0x" << std::setw(2 * sizeof(void*)) << std::setfill('0') << std::hex << reinterpret_cast<uintptr_t>(stack[i]) << "]";
- if (lines && lines[i])
- os << " " << lines[i];
- os << std::endl;
- }
- }
-
- std::string exception::print(const print_flags& flags) const
- {
- std::ostringstream os;
- print(os, flags);
- return os.str();
- }
-
- const std::string& exception::to_string() const
- {
- if (_msg_cache_empty)
- {
- _msg_cache = print();
- _msg_cache_empty = false;
- }
- return _msg_cache;
- }
-
- const char* exception::what() const throw()
- { return to_string().c_str(); }
-
- void exception::print_message(std::ostream& os) const
- {
- os << message;
- }
-
- std::ostream& operator <<(std::ostream& os, const exception& ex)
- {
- ex.print(os);
- return os;
- }
-
- /* error_exception */
-
- error_exception::error_exception(int e)
- : exception (std::to_string(e) + " - " + strerror(e))
- , error (e)
- { }
-
- error_exception::error_exception(const std::string& msg, int e) :
- exception(msg + ": " + std::to_string(e) + " - " + strerror(e)),
- error(e)
- { }
-
- /* range_exception */
-
- range_exception::range_exception(size_t mi, size_t ma, size_t idx, std::string msg)
- : exception (msg)
- , min (mi)
- , max (ma)
- , index (idx)
- { }
-
- void range_exception::print_message(std::ostream& os) const
- {
- os << "index out of range (min=" << min << "; max=" << max << "; index=" << index << ")";
- if (!message.empty())
- os << " - " << message;
- }
-
- /* argument_exception */
-
- argument_exception::argument_exception(std::string arg, std::string msg)
- : exception (msg)
- , argument (arg)
- { }
-
- void argument_exception::print_message(std::ostream& os) const
- {
- os << "invalid argument";
- if (!argument.empty())
- os << "(" << argument << ")";
- if (!message.empty())
- os << " - " << message;
- }
-
- }
|