Error.cpp 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/Completion.h>
  8. #include <LibJS/Runtime/Error.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. Error* Error::create(GlobalObject& global_object)
  12. {
  13. return global_object.heap().allocate<Error>(global_object, *global_object.error_prototype());
  14. }
  15. Error* Error::create(GlobalObject& global_object, String const& message)
  16. {
  17. auto& vm = global_object.vm();
  18. auto* error = Error::create(global_object);
  19. u8 attr = Attribute::Writable | Attribute::Configurable;
  20. error->define_direct_property(vm.names.message, js_string(vm, message), attr);
  21. return error;
  22. }
  23. Error::Error(Object& prototype)
  24. : Object(prototype)
  25. {
  26. }
  27. // 20.5.8.1 InstallErrorCause ( O, options ), https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
  28. ThrowCompletionOr<void> Error::install_error_cause(Value options)
  29. {
  30. auto& vm = this->vm();
  31. // 1. If Type(options) is Object and ? HasProperty(options, "cause") is true, then
  32. if (options.is_object() && TRY(options.as_object().has_property(vm.names.cause))) {
  33. // a. Let cause be ? Get(options, "cause").
  34. auto cause = TRY(options.as_object().get(vm.names.cause));
  35. // b. Perform ! CreateNonEnumerableDataPropertyOrThrow(O, "cause", cause).
  36. MUST(create_non_enumerable_data_property_or_throw(vm.names.cause, cause));
  37. }
  38. // Return NormalCompletion(undefined).
  39. return {};
  40. }
  41. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  42. ClassName* ClassName::create(GlobalObject& global_object) \
  43. { \
  44. return global_object.heap().allocate<ClassName>(global_object, *global_object.snake_name##_prototype()); \
  45. } \
  46. \
  47. ClassName* ClassName::create(GlobalObject& global_object, String const& message) \
  48. { \
  49. auto& vm = global_object.vm(); \
  50. auto* error = ClassName::create(global_object); \
  51. u8 attr = Attribute::Writable | Attribute::Configurable; \
  52. error->define_direct_property(vm.names.message, js_string(vm, message), attr); \
  53. return error; \
  54. } \
  55. \
  56. ClassName::ClassName(Object& prototype) \
  57. : Error(prototype) \
  58. { \
  59. }
  60. JS_ENUMERATE_NATIVE_ERRORS
  61. #undef __JS_ENUMERATE
  62. }