A given value is out of the accepted range.
Production Risk
High. An out-of-range error can cause a process crash and often signals a serious logic flaw in handling data collections or boundaries.
This error indicates that a numeric value is outside the acceptable range for a specific operation or data type. It is commonly seen when working with buffers, arrays, or other data structures with fixed size limits. For example, trying to access an array index that does not exist will cause this type of error.
- 1An attempt was made to access an array or buffer element at an index that is less than zero or greater than or equal to its length.
- 2A numeric argument for a function exceeds its minimum or maximum allowed value.
- 3A calculation results in a number that cannot be represented within the target data type's limits.
This error is typically thrown when performing index-based access on data structures or when a numeric argument must fit within a specific, defined range.
const buf = Buffer.from('hello');
// The buffer has a length of 5. Index 10 is out of range.
try {
console.log(buf.readInt8(10));
} catch (err) {
console.error(err);
}expected output
RangeError [ERR_OUT_OF_RANGE]: The value of 'offset' is out of range. It must be >= 0 and <= 4. Received 10
Fix
Perform Boundary Checks
WHEN Accessing elements in an array, buffer, or other indexed collection.
const buf = Buffer.from('hello');
const index = 10;
if (index >= 0 && index < buf.length) {
console.log(buf.readInt8(index));
} else {
console.error('Index is out of buffer range.');
}Why this works
Before attempting to access an index, always verify that it is within the valid bounds (from 0 to length - 1) of the data structure.
const buf = Buffer.from('hello');
// The buffer has a length of 5. Index 10 is out of range.
try {
console.log(buf.readInt8(10));
} catch (err) {
console.error(err); // this triggers ERR_OUT_OF_RANGEtry {
// operation that may throw ERR_OUT_OF_RANGE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_OUT_OF_RANGE') {
console.error('ERR_OUT_OF_RANGE:', err.message)
} else {
throw err
}
}const buf = Buffer.from('hello')
const idx = 2
if (idx >= 0 && idx < buf.length) {
console.log(buf.readInt8(idx))
}✕
✕
https://github.com/nodejs/node/blob/main/lib/internal/errors.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev