Error.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. public:
  26. static NonnullGCPtr<Error> create(Realm&);
  27. static NonnullGCPtr<Error> create(Realm&, String message);
  28. static NonnullGCPtr<Error> create(Realm&, StringView message);
  29. virtual ~Error() override = default;
  30. [[nodiscard]] String stack_string(CompactTraceback compact = CompactTraceback::No) const;
  31. ThrowCompletionOr<void> install_error_cause(Value options);
  32. Vector<TracebackFrame, 32> const& traceback() const { return m_traceback; }
  33. protected:
  34. explicit Error(Object& prototype);
  35. private:
  36. void populate_stack();
  37. Vector<TracebackFrame, 32> m_traceback;
  38. };
  39. // NOTE: Making these inherit from Error is not required by the spec but
  40. // our way of implementing the [[ErrorData]] internal slot, which is
  41. // used in Object.prototype.toString().
  42. #define DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName) \
  43. class ClassName final : public Error { \
  44. JS_OBJECT(ClassName, Error); \
  45. \
  46. public: \
  47. static NonnullGCPtr<ClassName> create(Realm&); \
  48. static NonnullGCPtr<ClassName> create(Realm&, String message); \
  49. static NonnullGCPtr<ClassName> create(Realm&, StringView message); \
  50. \
  51. explicit ClassName(Object& prototype); \
  52. virtual ~ClassName() override = default; \
  53. };
  54. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  55. DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName)
  56. JS_ENUMERATE_NATIVE_ERRORS
  57. #undef __JS_ENUMERATE
  58. }