An invalid HTTP status code was used.
Production Risk
Medium. This is a clear programming error that will cause a request to fail, but it is usually specific to one code path and does not crash the server.
This error occurs when you attempt to set an invalid HTTP status code on a server response. HTTP status codes must be a 3-digit integer between 100 and 599 (inclusive). Providing a number outside this range, or a non-integer value, will cause Node.js to throw this error to prevent sending a non-compliant HTTP response.
- 1Setting `res.statusCode` to a number less than 100 or greater than 599.
- 2Accidentally passing a string or other non-numeric value to `res.statusCode`.
- 3A bug in code that dynamically calculates a status code, resulting in an invalid value.
This error is thrown by the HTTP server response object when the `statusCode` property is set to a value that fails the valid range check.
const http = require('http');
const server = http.createServer((req, res) => {
try {
res.statusCode = 999; // Invalid status code
res.end('This will not be sent');
} catch (err) {
// Node.js might handle this internally and close the socket
console.error(err.code);
}
});
server.listen(3000);expected output
ERR_HTTP_INVALID_STATUS_CODE
Fix
Use a Valid HTTP Status Code
WHEN Setting the status code of an HTTP response.
const server = http.createServer((req, res) => {
// Use a valid, standard status code.
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
});Why this works
Ensure that any value set for `res.statusCode` is a number within the valid 100-599 range. Refer to the IANA registry for a list of valid HTTP status codes.
const http = require('http');
const server = http.createServer((req, res) => {
try {
res.statusCode = 999; // Invalid status code
res.end('This will not be sent');
} catch (err) { // this triggers ERR_HTTP_INVALID_STATUS_CODEtry {
// operation that may throw ERR_HTTP_INVALID_STATUS_CODE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_INVALID_STATUS_CODE') {
console.error('ERR_HTTP_INVALID_STATUS_CODE:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_invalid_status_code(...args) {
// validate args here
return performOperation(...args)
}✕
✕
https://github.com/nodejs/node/blob/main/lib/_http_common.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev