Modify rule S3696: Adapt to LaYC (#2400)

This commit is contained in:
Yassin Kammoun 2023-07-06 09:34:55 +02:00 committed by GitHub
parent 34a1521117
commit 7ff4f550bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,26 +1,31 @@
== Why is this an issue?
It is a bad practice to ``++throw++`` something that's not derived at some level from ``++Error++``. If you can't find an existing ``++Error++`` type that suitably conveys what you need to convey, then you should extend ``++Error++`` to create one.
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.
Specifically, part of the point of throwing ``++Error++``s is to communicate about the conditions of the error, but literals have far less ability to communicate meaningfully than ``++Error++``s because they don't include stacktraces.
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.
=== Noncompliant code example
[source,javascript]
[source,javascript,diff-id=1,diff-type=noncompliant]
----
throw 404; // Noncompliant
throw "Invalid negative index."; // Noncompliant
----
=== Compliant solution
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]
[source,javascript,diff-id=1,diff-type=compliant]
----
throw new Error("Status: " + 404);
throw new Error("Invalid negative index.");{code}
throw new RangeError("Invalid negative index.");
----
== Resources
=== Documentation
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw[MDN - ``++throw++``]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error[MDN - Error]
ifdef::env-github,rspecator-view[]
'''