exception.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #pragma once
  2. #include <exception>
  3. #include <string>
  4. #include <vector>
  5. #include <utility>
  6. namespace nkg {
  7. class exception : public std::exception {
  8. private:
  9. int m_source_line;
  10. std::string m_source_file;
  11. std::string m_custom_message;
  12. std::vector<std::string> m_hints;
  13. public:
  14. exception(std::string_view file, int line, std::string_view message) noexcept :
  15. std::exception(), // don't pass `char*` to `std::exception`, because it is not documented in c++ standard.
  16. m_source_line(line),
  17. m_source_file(file),
  18. m_custom_message(message) {}
  19. [[nodiscard]]
  20. int source_line() const noexcept {
  21. return m_source_line;
  22. }
  23. [[nodiscard]]
  24. const std::string& source_file() const noexcept {
  25. return m_source_file;
  26. }
  27. [[nodiscard]]
  28. const std::string& custom_message() const noexcept {
  29. return m_custom_message;
  30. }
  31. exception& push_hint(std::string_view hint) noexcept {
  32. m_hints.emplace_back(hint);
  33. return *this;
  34. }
  35. exception& pop_hint() noexcept {
  36. m_hints.pop_back();
  37. return *this;
  38. }
  39. const std::vector<std::string>& hints() const noexcept {
  40. return m_hints;
  41. }
  42. virtual const char* what() const noexcept override {
  43. return m_custom_message.c_str();
  44. }
  45. [[nodiscard]]
  46. virtual bool error_code_exists() const noexcept {
  47. return false;
  48. }
  49. [[nodiscard]]
  50. virtual intptr_t error_code() const noexcept {
  51. #if _MSC_VER
  52. __debugbreak();
  53. __assume(false);
  54. #elif defined(__GNUC__) || defined(__GNUG__) || defined(__clang__)
  55. __builtin_trap();
  56. __builtin_unreachable();
  57. #else
  58. #error "exception.hpp: unknown compiler is detected."
  59. #endif
  60. }
  61. [[nodiscard]]
  62. virtual const std::string& error_string() const noexcept {
  63. #if _MSC_VER
  64. __debugbreak();
  65. __assume(false);
  66. #elif defined(__GNUC__) || defined(__GNUG__) || defined(__clang__)
  67. __builtin_trap();
  68. __builtin_unreachable();
  69. #else
  70. #error "exception.hpp: unknown compiler is detected."
  71. #endif
  72. }
  73. virtual ~exception() = default;
  74. };
  75. }