Error.h 2.8 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. struct UnrealizedSourceRange {
  18. u32 start_offset { 0 };
  19. u32 end_offset { 0 };
  20. RefPtr<JS::SourceCode const> source_code;
  21. };
  22. mutable Variant<SourceRange, UnrealizedSourceRange> source_range_storage;
  23. };
  24. class Error : public Object {
  25. JS_OBJECT(Error, Object);
  26. public:
  27. static NonnullGCPtr<Error> create(Realm&);
  28. static NonnullGCPtr<Error> create(Realm&, String message);
  29. static ThrowCompletionOr<NonnullGCPtr<Error>> create(Realm&, StringView message);
  30. virtual ~Error() override = default;
  31. [[nodiscard]] ThrowCompletionOr<String> stack_string(VM&) 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. \
  47. public: \
  48. static NonnullGCPtr<ClassName> create(Realm&); \
  49. static NonnullGCPtr<ClassName> create(Realm&, String message); \
  50. static ThrowCompletionOr<NonnullGCPtr<ClassName>> create(Realm&, StringView message); \
  51. \
  52. explicit ClassName(Object& prototype); \
  53. virtual ~ClassName() override = default; \
  54. };
  55. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  56. DECLARE_NATIVE_ERROR(ClassName, snake_name, PrototypeName, ConstructorName)
  57. JS_ENUMERATE_NATIVE_ERRORS
  58. #undef __JS_ENUMERATE
  59. }