Skip to main content

Error Types

QuickJS provides constructor functions for all standard JavaScript error types. These functions create error objects with the appropriate prototype and can optionally throw them immediately.

Error Constructors

Each error constructor creates a new error object with a formatted message.

JS_NewError

Creates a generic Error object.
Creates an empty Error object. You typically add a message property yourself. Example:

JS_NewRangeError

Creates a RangeError with a formatted message.
Use this for errors indicating a value is outside the acceptable range. Example:

JS_NewReferenceError

Creates a ReferenceError with a formatted message.
Use this for errors related to invalid references or undefined variables. Example:

JS_NewSyntaxError

Creates a SyntaxError with a formatted message.
Use this for syntax-related errors, typically during parsing. Example:

JS_NewTypeError

Creates a TypeError with a formatted message.
Use this for type-related errors, such as invalid argument types. Example:

JS_NewInternalError

Creates an InternalError with a formatted message.
Use this for internal engine errors. Example:

Throwing Functions

For convenience, QuickJS provides functions that both create and throw errors in one call. These functions always return JS_EXCEPTION.

JS_ThrowRangeError

Example:

JS_ThrowReferenceError

Example:

JS_ThrowSyntaxError

Example:

JS_ThrowTypeError

Example:

JS_ThrowInternalError

Example:

Additional Error Functions

JS_ThrowOutOfMemory

Throws an out-of-memory error.
Example:

JS_ThrowDOMException

Creates and throws a DOMException with a name and message.
Example:

Format Strings

All error constructor and throwing functions that accept format strings support standard printf-style formatting:

Choosing the Right Error Type

Best Practices

  1. Use specific error types: Choose the most appropriate error type for the situation.
  2. Provide context: Include relevant values and context in error messages.
  3. Be consistent: Use the same error type for similar situations throughout your code.
  4. Use throwing functions for simplicity: JS_ThrowTypeError() is more concise than JS_Throw(ctx, JS_NewTypeError()).

Example: Comprehensive Error Handling

See Also