Throw a Literal Value
ID |
javascript.no_throw_literal |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
best-practice, reliability |
Description
Reports throw statements whose argument is a bare literal value: a string, number, boolean, null, undefined, object literal, array literal, regex, or template literal. JavaScript permits throwing any value, but only Error instances carry a stack trace and are recognised by the standard instanceof Error discrimination in catch handlers.
Rationale
Throwing a non-Error value:
-
Loses the stack trace — the value crosses the catch boundary with no information about where it originated.
-
Breaks
try { … } catch (e) { if (e instanceof Error) … }patterns and TypeScript’s narrowing ofunknownin catch. -
Produces unhelpful messages in unhandled-rejection / uncaught-exception logs.
-
Forces every catch handler that wants the stack to wrap the thrown value, which is easy to forget.
// Bad
throw "Order not found";
throw { code: 404 };
throw null;
Remediation
Throw an Error (or a domain-specific subclass) so the runtime captures the stack and downstream handlers can rely on the standard contract.
// Good
throw new Error("Order not found");
throw new NotFoundError("Order not found", { code: 404 });
If you need to attach extra data, set properties on the Error instance or define a subclass — don’t throw a bare object.