Constructs a new ScriptError
.
A description of the error.
Optional
cause: Error(Optional) The original error that caused this one. If provided the exception message will have a reference to the cause.
Optional
cause(Optional) The original error that caused this one. If provided the exception message will have a reference to the cause.
Optional
stackStatic
stackThe Error.stackTraceLimit
property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack
or
Error.captureStackTrace(obj)
).
The default value is 10
but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Utility method to rethrow the deepest original cause if present,
otherwise rethrows this ScriptError
itself.
Useful for deferring a controlled exception and then
surfacing the root cause explicitly.
Override toString() method.
The name and the message on the first line, then on the second line the Stack trace section name, i.e. 'Stack trace:'. Starting on the third line the stack trace information. If a cause was provided the stack trace will refer to the cause otherwise to the original exception.
Static
captureCreates a .stack
property on targetObject
, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace()
was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}
.
The optional constructorOpt
argument accepts a function. If given, all frames
above constructorOpt
, including constructorOpt
, will be omitted from the
generated stack trace.
The constructorOpt
argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
Optional
constructorOpt: FunctionStatic
prepare
A custom error class for domain-specific or script-level exceptions. Designed to provide clarity and structure when handling expected or controlled failures in scripts (e.g., logging or validation errors). It supports error chaining through an optional
cause
parameter, preserving the original stack trace. Prefer usingScriptError
for intentional business logic errors or internal errors to distinguish them from unexpected system-level failures.Example