error.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /*
  2. * Copyright 2010-2016 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
  4. */
  5. #ifndef BX_ERROR_H_HEADER_GUARD
  6. #define BX_ERROR_H_HEADER_GUARD
  7. #include "bx.h"
  8. #include "string.h"
  9. #define BX_ERROR_SET(_ptr, _result, _msg) \
  10. BX_MACRO_BLOCK_BEGIN \
  11. BX_TRACE("Error %d: %s", _result.code, "" _msg); \
  12. _ptr->setError(_result, "" _msg); \
  13. BX_MACRO_BLOCK_END
  14. #define BX_ERROR_USE_TEMP_WHEN_NULL(_ptr) \
  15. const bx::Error tmpError; /* It should not be used directly! */ \
  16. _ptr = NULL == _ptr ? const_cast<bx::Error*>(&tmpError) : _ptr
  17. #define BX_ERROR_SCOPE(_ptr) \
  18. BX_ERROR_USE_TEMP_WHEN_NULL(_ptr); \
  19. bx::ErrorScope bxErrorScope(const_cast<bx::Error*>(&tmpError) )
  20. #define BX_ERROR_RESULT(_err, _code) \
  21. BX_STATIC_ASSERT(_code != 0, "ErrorCode 0 is reserved!"); \
  22. static const bx::ErrorResult _err = { _code }
  23. namespace bx
  24. {
  25. ///
  26. struct ErrorResult
  27. {
  28. uint32_t code;
  29. };
  30. ///
  31. class Error
  32. {
  33. BX_CLASS(Error
  34. , NO_COPY
  35. , NO_ASSIGNMENT
  36. );
  37. public:
  38. Error()
  39. : m_code(0)
  40. {
  41. }
  42. void reset()
  43. {
  44. m_code = 0;
  45. m_msg.clear();
  46. }
  47. void setError(ErrorResult _errorResult, const StringView& _msg)
  48. {
  49. BX_CHECK(0 != _errorResult.code, "Invalid ErrorResult passed to setError!");
  50. if (!isOk() )
  51. {
  52. return;
  53. }
  54. m_code = _errorResult.code;
  55. m_msg = _msg;
  56. }
  57. bool isOk() const
  58. {
  59. return 0 == m_code;
  60. }
  61. ErrorResult get() const
  62. {
  63. ErrorResult result = { m_code };
  64. return result;
  65. }
  66. const StringView& getMessage() const
  67. {
  68. return m_msg;
  69. }
  70. bool operator==(const ErrorResult& _rhs) const
  71. {
  72. return _rhs.code == m_code;
  73. }
  74. bool operator!=(const ErrorResult& _rhs) const
  75. {
  76. return _rhs.code != m_code;
  77. }
  78. private:
  79. StringView m_msg;
  80. uint32_t m_code;
  81. };
  82. ///
  83. class ErrorScope
  84. {
  85. BX_CLASS(ErrorScope
  86. , NO_COPY
  87. , NO_ASSIGNMENT
  88. );
  89. public:
  90. ErrorScope(Error* _err)
  91. : m_err(_err)
  92. {
  93. BX_CHECK(NULL != _err, "_err can't be NULL");
  94. }
  95. ~ErrorScope()
  96. {
  97. BX_CHECK(m_err->isOk(), "Error: %d", m_err->get().code);
  98. }
  99. private:
  100. Error* m_err;
  101. };
  102. } // namespace bx
  103. #endif // BX_ERROR_H_HEADER_GUARD