Error.cpp 3.8 KB

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