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.JS_NewRangeError
Creates a RangeError with a formatted message.JS_NewReferenceError
Creates a ReferenceError with a formatted message.JS_NewSyntaxError
Creates a SyntaxError with a formatted message.JS_NewTypeError
Creates a TypeError with a formatted message.JS_NewInternalError
Creates an InternalError with a formatted message.Throwing Functions
For convenience, QuickJS provides functions that both create and throw errors in one call. These functions always returnJS_EXCEPTION.
JS_ThrowRangeError
JS_ThrowReferenceError
JS_ThrowSyntaxError
JS_ThrowTypeError
JS_ThrowInternalError
Additional Error Functions
JS_ThrowOutOfMemory
Throws an out-of-memory error.JS_ThrowDOMException
Creates and throws a DOMException with a name and message.Format Strings
All error constructor and throwing functions that accept format strings support standard printf-style formatting:Choosing the Right Error Type
| Error Type | Use When |
|---|---|
| Error | Generic errors that don’t fit other categories |
| RangeError | A numeric value is outside the allowed range |
| ReferenceError | Referencing an undefined or inaccessible variable |
| SyntaxError | Parsing or compiling code fails |
| TypeError | A value is not of the expected type |
| InternalError | Engine internal errors or assertions fail |
Best Practices
- Use specific error types: Choose the most appropriate error type for the situation.
- Provide context: Include relevant values and context in error messages.
- Be consistent: Use the same error type for similar situations throughout your code.
- Use throwing functions for simplicity:
JS_ThrowTypeError()is more concise thanJS_Throw(ctx, JS_NewTypeError()).
Example: Comprehensive Error Handling
See Also
- Throwing Exceptions - Creating and throwing exceptions
- Catching Exceptions - Retrieving and handling exceptions