esp_exception.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #pragma once
  7. #ifdef __cpp_exceptions
  8. #include "esp_err.h"
  9. #include <exception>
  10. namespace idf {
  11. /**
  12. * @brief
  13. * General exception class for all C++ exceptions in IDF.
  14. *
  15. * All throwing code in IDF should use either this exception directly or a sub-classes.
  16. * An error from the underlying IDF function is mandatory. The idea is to wrap the orignal IDF error code to keep
  17. * the error scheme partially compatible. If an exception occurs in a higher level C++ code not directly wrapping
  18. * IDF functions, an appropriate error code reflecting the cause must be chosen or newly created.
  19. */
  20. class ESPException : public std::exception {
  21. public:
  22. /**
  23. * @param error Error from underlying IDF functions.
  24. */
  25. ESPException(esp_err_t error);
  26. virtual ~ESPException() { }
  27. /**
  28. * @return A textual representation of the contained error. This method only wraps \c esp_err_to_name.
  29. */
  30. virtual const char *what() const noexcept;
  31. /**
  32. * Error from underlying IDF functions. If an exception occurs in a higher level C++ code not directly wrapping
  33. * IDF functions, an appropriate error code reflecting the cause must be chosen or newly created.
  34. */
  35. const esp_err_t error;
  36. };
  37. /**
  38. * Convenience macro to help converting IDF error codes into ESPException.
  39. */
  40. #define CHECK_THROW(error_) \
  41. do { \
  42. esp_err_t result = error_; \
  43. if (result != ESP_OK) throw idf::ESPException(result); \
  44. } while (0)
  45. /**
  46. * Convenience macro to help converting IDF error codes into a child of ESPException.
  47. */
  48. #define CHECK_THROW_SPECIFIC(error_, exception_type_) \
  49. do { \
  50. esp_err_t result = (error_); \
  51. if (result != ESP_OK) throw idf::exception_type_(result); \
  52. } while (0)
  53. } // namespace idf
  54. #endif // __cpp_exceptions