Error.cpp 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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())
  33. return {};
  34. auto has_property = options.as_object().has_property(vm.names.cause);
  35. if (auto* exception = vm.exception())
  36. return throw_completion(exception->value());
  37. if (has_property) {
  38. // a. Let cause be ? Get(options, "cause").
  39. auto cause = options.as_object().get(vm.names.cause);
  40. if (auto* exception = vm.exception())
  41. return throw_completion(exception->value());
  42. // b. Perform ! CreateNonEnumerableDataPropertyOrThrow(O, "cause", cause).
  43. create_non_enumerable_data_property_or_throw(vm.names.cause, cause);
  44. }
  45. // Return NormalCompletion(undefined).
  46. return {};
  47. }
  48. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  49. ClassName* ClassName::create(GlobalObject& global_object) \
  50. { \
  51. return global_object.heap().allocate<ClassName>(global_object, *global_object.snake_name##_prototype()); \
  52. } \
  53. \
  54. ClassName* ClassName::create(GlobalObject& global_object, String const& message) \
  55. { \
  56. auto& vm = global_object.vm(); \
  57. auto* error = ClassName::create(global_object); \
  58. u8 attr = Attribute::Writable | Attribute::Configurable; \
  59. error->define_direct_property(vm.names.message, js_string(vm, message), attr); \
  60. return error; \
  61. } \
  62. \
  63. ClassName::ClassName(Object& prototype) \
  64. : Error(prototype) \
  65. { \
  66. }
  67. JS_ENUMERATE_NATIVE_ERRORS
  68. #undef __JS_ENUMERATE
  69. }