esp_exception.hpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #pragma once
  15. #ifdef __cpp_exceptions
  16. #include "esp_err.h"
  17. #include <exception>
  18. namespace idf {
  19. /**
  20. * @brief
  21. * General exception class for all C++ exceptions in IDF.
  22. *
  23. * All throwing code in IDF should use either this exception directly or a sub-classes.
  24. * An error from the underlying IDF function is mandatory. The idea is to wrap the orignal IDF error code to keep
  25. * the error scheme partially compatible. If an exception occurs in a higher level C++ code not directly wrapping
  26. * IDF functions, an appropriate error code reflecting the cause must be chosen or newly created.
  27. */
  28. class ESPException : public std::exception {
  29. public:
  30. /**
  31. * @param error Error from underlying IDF functions.
  32. */
  33. ESPException(esp_err_t error);
  34. virtual ~ESPException() { }
  35. /**
  36. * @return A textual representation of the contained error. This method only wraps \c esp_err_to_name.
  37. */
  38. virtual const char *what() const noexcept;
  39. /**
  40. * Error from underlying IDF functions. If an exception occurs in a higher level C++ code not directly wrapping
  41. * IDF functions, an appropriate error code reflecting the cause must be chosen or newly created.
  42. */
  43. const esp_err_t error;
  44. };
  45. /**
  46. * Convenience macro to help converting IDF error codes into ESPException.
  47. */
  48. #define CHECK_THROW(error_) \
  49. do { \
  50. esp_err_t result = error_; \
  51. if (result != ESP_OK) throw idf::ESPException(result); \
  52. } while (0)
  53. /**
  54. * Convenience macro to help converting IDF error codes into a child of ESPException.
  55. */
  56. #define CHECK_THROW_SPECIFIC(error_, exception_type_) \
  57. do { \
  58. esp_err_t result = error_; \
  59. if (result != ESP_OK) throw idf::exception_type_(result); \
  60. } while (0)
  61. } // namespace idf
  62. #endif // __cpp_exceptions