'clientError' 事件


如果客户端触发了一个 'error' 事件,则它会被传递到这里。 该事件的监听器负责关闭或销毁底层的 socket。 例如,用户可能希望更温和地用自定义的 HTTP 响应关闭 socket,而不是突然地切断连接。

默认情况下,如果可以会使用 HTTP '400 Bad Request' 响应关闭 socket,否则 socket 会被立即销毁。

socket 参数是发生错误的 net.Socket 对象。

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

'clientError' 事件发生时,不会有 requestresponse 对象,所以发送的任何 HTTP 响应,包括响应头和内容,必须被直接写入到 socket 对象。 必须确保响应是一个被正确格式化的 HTTP 响应消息。

err 是一个 Error 实例,包含以下两部分:

  • bytesParsed: Node.js 正确解析的请求包的字节数。
  • rawPacket: 当前请求的原始数据包。

If a client connection emits an 'error' event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.

Default behavior is to close the socket with an HTTP '400 Bad Request' response if possible, otherwise the socket is immediately destroyed.

socket is the net.Socket object that the error originated from.

const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

When the 'clientError' event occurs, there is no request or response object, so any HTTP response sent, including response headers and payload, must be written directly to the socket object. Care must be taken to ensure the response is a properly formatted HTTP response message.

err is an instance of Error with two extra columns:

  • bytesParsed: the bytes count of request packet that Node.js may have parsed correctly;
  • rawPacket: the raw packet of current request.