throw_error_handler.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2018-2025 Jean-Louis Leroy
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // See accompanying file LICENSE_1_0.txt
  4. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_OPENMETHOD_POLICY_THROW_ERROR_HPP
  6. #define BOOST_OPENMETHOD_POLICY_THROW_ERROR_HPP
  7. #include <boost/openmethod/preamble.hpp>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <string>
  11. namespace boost::openmethod::policies {
  12. //! Throws error as an exception.
  13. //!
  14. struct throw_error_handler : error_handler {
  15. //! A ErrorHandlerFn metafunction.
  16. //!
  17. //! @tparam Registry The registry containing this policy.
  18. template<class Registry>
  19. class fn {
  20. public:
  21. //! Throws the error.
  22. //!
  23. //! Wraps the error in an object that can be caught either as an
  24. //! `Error`, or as a `std::runtime_error`, and throws it as an exception.
  25. //!
  26. //! @tparam Error A subclass of @ref openmethod_error.
  27. //! @param error The error object.
  28. template<class Error>
  29. [[noreturn]] static auto error(const Error& error) -> void {
  30. struct wrapper : Error, std::runtime_error {
  31. wrapper(const Error& error, std::string&& description)
  32. : Error(error), std::runtime_error(description) {
  33. }
  34. };
  35. std::ostringstream os;
  36. error.template write<Registry>(os);
  37. throw wrapper(error, os.str());
  38. }
  39. };
  40. };
  41. } // namespace boost::openmethod::policies
  42. #endif