Error.h 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/DeprecatedFlyString.h>
  9. #include <AK/String.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/Object.h>
  12. #include <LibJS/SourceRange.h>
  13. namespace JS {
  14. struct TracebackFrame {
  15. DeprecatedFlyString function_name;
  16. [[nodiscard]] SourceRange const& source_range() const;
  17. mutable Variant<SourceRange, UnrealizedSourceRange> source_range_storage;
  18. };
  19. enum CompactTraceback {
  20. No,
  21. Yes,
  22. };
  23. class Error : public Object {
  24. JS_OBJECT(Error, Object);
  25. JS_DECLARE_ALLOCATOR(Error);
  26. public:
  27. static NonnullGCPtr<Error> create(Realm&);
  28. static NonnullGCPtr<Error> create(Realm&, String message);
  29. static NonnullGCPtr<Error> create(Realm&, StringView message);
  30. virtual ~Error() override = default;
  31. [[nodiscard]] String stack_string(CompactTraceback compact = CompactTraceback::No) const;
  32. ThrowCompletionOr<void> install_error_cause(Value options);
  33. Vector<TracebackFrame, 32> const& traceback() const { return m_traceback; }
  34. protected:
  35. explicit Error(Object& prototype);
  36. private:
  37. void populate_stack();
  38. Vector<TracebackFrame, 32> m_traceback;
  39. };
  40. // NOTE: Making these inherit from Error is not required by the spec but
  41. // our way of implementing the [[ErrorData]] internal slot, which is
  42. // used in Object.prototype.toString().
  43. #define DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName) \
  44. class ClassName final : public Error { \
  45. JS_OBJECT(ClassName, Error); \
  46. JS_DECLARE_ALLOCATOR(ClassName); \
  47. \
  48. public: \
  49. static NonnullGCPtr<ClassName> create(Realm&); \
  50. static NonnullGCPtr<ClassName> create(Realm&, String message); \
  51. static NonnullGCPtr<ClassName> create(Realm&, StringView message); \
  52. \
  53. explicit ClassName(Object& prototype); \
  54. virtual ~ClassName() override = default; \
  55. };
  56. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  57. DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName)
  58. JS_ENUMERATE_NATIVE_ERRORS
  59. #undef __JS_ENUMERATE
  60. }