46 lines
1.8 KiB
Plaintext
46 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In JavaScript, throwing literals (primitive values like strings, numbers, booleans, etc.) as exceptions is generally discouraged. While it is syntactically valid to throw literals, it is considered a best practice to throw instances of the ``++Error++`` class or its subclasses instead.
|
|
|
|
Throwing an instance of the ``++Error++`` class allows you to provide more meaningful information about the error.
|
|
|
|
The ``++Error++`` class and its subclasses provide properties like ``++message++`` and ``++stack++`` that can be used to convey useful details about the error, such as a description of the problem, the context in which it occurred, or a stack trace for debugging.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
throw 404; // Noncompliant
|
|
throw "Invalid negative index."; // Noncompliant
|
|
----
|
|
|
|
Throwing literals can make it harder to handle and differentiate between different types of errors. Instead, you should use one of the exception types specifically created for the purpose or define your own subclass of the ``++Error++`` class.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
throw new Error("Status: " + 404);
|
|
throw new RangeError("Invalid negative index.");
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw[``++throw++``]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error[Error]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|