ExceptionOr.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/NonnullRefPtr.h>
  8. #include <AK/Optional.h>
  9. #include <AK/RefPtr.h>
  10. #include <LibWeb/DOM/DOMException.h>
  11. namespace Web::DOM {
  12. #define ENUMERATE_SIMPLE_WEBIDL_EXCEPTION_TYPES(E) \
  13. E(EvalError) \
  14. E(RangeError) \
  15. E(ReferenceError) \
  16. E(TypeError) \
  17. E(URIError)
  18. #define E(x) x,
  19. enum class SimpleExceptionType {
  20. ENUMERATE_SIMPLE_WEBIDL_EXCEPTION_TYPES(E)
  21. };
  22. #undef E
  23. struct SimpleException {
  24. SimpleExceptionType type;
  25. String message;
  26. };
  27. template<typename ValueType>
  28. class ExceptionOr {
  29. public:
  30. ExceptionOr() requires(IsSame<ValueType, Empty>)
  31. : m_result(Empty {})
  32. {
  33. }
  34. ExceptionOr(const ValueType& result)
  35. : m_result(result)
  36. {
  37. }
  38. ExceptionOr(ValueType&& result)
  39. : m_result(move(result))
  40. {
  41. }
  42. ExceptionOr(NonnullRefPtr<DOMException> exception)
  43. : m_exception(move(exception))
  44. {
  45. }
  46. ExceptionOr(SimpleException exception)
  47. : m_exception(move(exception))
  48. {
  49. }
  50. ExceptionOr(Variant<SimpleException, NonnullRefPtr<DOMException>> exception)
  51. : m_exception(move(exception).template downcast<Empty, SimpleException, NonnullRefPtr<DOMException>>())
  52. {
  53. }
  54. ExceptionOr(ExceptionOr&& other) = default;
  55. ExceptionOr(const ExceptionOr& other) = default;
  56. ~ExceptionOr() = default;
  57. ValueType& value() requires(!IsSame<ValueType, Empty>)
  58. {
  59. return m_result.value();
  60. }
  61. ValueType release_value()
  62. {
  63. return m_result.release_value();
  64. }
  65. Variant<SimpleException, NonnullRefPtr<DOMException>> exception() const
  66. {
  67. return m_exception.template downcast<SimpleException, NonnullRefPtr<DOMException>>();
  68. }
  69. bool is_exception() const
  70. {
  71. return !m_exception.template has<Empty>();
  72. }
  73. // These are for compatibility with the TRY() macro in AK.
  74. [[nodiscard]] bool is_error() const { return is_exception(); }
  75. Variant<SimpleException, NonnullRefPtr<DOMException>> release_error() { return exception(); }
  76. private:
  77. Optional<ValueType> m_result;
  78. // https://webidl.spec.whatwg.org/#idl-exceptions
  79. Variant<Empty, SimpleException, NonnullRefPtr<DOMException>> m_exception {};
  80. };
  81. template<>
  82. class ExceptionOr<void> : public ExceptionOr<Empty> {
  83. public:
  84. using ExceptionOr<Empty>::ExceptionOr;
  85. };
  86. }