Request error socket hang up

I'm building a web scraper with Node and Cheerio, and for a certain website I'm getting the following error (it only happens on this one website, no others that I try to scrape. It happens at a

There are two cases when socket hang up gets thrown:

When you are a client

When you, as a client, send a request to a remote server, and receive no timely response. Your socket is ended which throws this error. You should catch this error and decide how to handle it: whether retry the request, queue it for later, etc.

When you are a server/proxy

When you, as a server, perhaps a proxy server, receive a request from a client, then start acting upon it (or relay the request to the upstream server), and before you have prepared the response, the client decides to cancel/abort the request.

This stack trace shows what happens when a client cancels the request.

Trace: { [Error: socket hang up] code: 'ECONNRESET' }
    at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
    at ClientRequest.emit (events.js:117:20)
    at Socket.socketCloseListener (http.js:1526:9)
    at Socket.emit (events.js:95:17)
    at TCP.close (net.js:465:12)

Line http.js:1526:9points to the same socketCloseListener mentioned by @Blender, particularly:

// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());

...

function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;
}

This is a typical case if the client is a user in the browser. The request to load some resource/page takes long, and users simply refresh the page. Such action causes the previous request to get aborted which on your server side throws this error.

Since this error is caused by the wish of a client, they don’t expect to receive any error message. So, no need to consider this error as critical. Just ignore it. This is encouraged by the fact that on such error the res socket that your client listened to is, though still writable, destroyed.

console.log(res.socket.destroyed); //true

So, no point to send anything, except explicitly closing the response object:

res.end();

However, what you should do for sure if you are a proxy server which has already relayed the request to the upstream, is to abort your internal request to the upstream, indicating your lack of interest in the response, which in turn will tell the upstream server to, perhaps, stop an expensive operation.

When a socket hang up is thrown, one of two things happens:

When you’re a customer,

When you send a request to a distant server as a client and don’t get a response in a timely manner. This error is caused by the end of your socket. You should catch this error and decide what to do with it, such as retrying the request or queueing it for later.

If you’re a server or proxy,

When you, as a server, possibly a proxy server, get a request from a client and begin acting on it (or relaying the request to the upstream server), the client decides to cancel/abort the request before you have finished preparing the response.

When a customer cancels a request, this stack trace depicts what happened.

Trace: { [Error: socket hang up] code: 'ECONNRESET' }
    at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
    at ClientRequest.emit (events.js:117:20)
    at Socket.socketCloseListener (http.js:1526:9)
    at Socket.emit (events.js:95:17)
    at TCP.close (net.js:465:12)

Line http.js:1526:9points to the same socketCloseListener mentioned by @Blender, particularly:

// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());

...

function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;
}

If the client is a browser user, this is a common scenario. When a request for a resource/page takes a long time to load, visitors simply refresh the page. As a result of this action, the previous request is cancelled, resulting in this error on your server.

Because this issue is the result of a client’s request, they should not expect to receive an error notice. As a result, there’s no reason to consider this error to be important. Simply disregard it. This is bolstered by the fact that on such an error, the res socket that your client was listening to is destroyed, despite the fact that it is still editable.

console.log(res.socket.destroyed); //true

So, no point to send anything, except explicitly closing the response object:

res.end();

However, if you are a proxy server that has already transmitted the request to the upstream, you should abort your internal request to the upstream, signalling that you are uninterested in the response, which will alert the upstream server to maybe halt an expensive activity.

Есть два случая, когда socket hang up бросается:

Когда вы клиент

Когда вы, как клиент, отправляете запрос на удаленный сервер и не получаете своевременного ответа. Ваш сокет завершен, что вызывает эту ошибку. Вы должны поймать эту ошибку и решить, как с ней справиться: повторить ли запрос, поставить его в очередь на потом и т. д.

Когда вы сервер/прокси

Когда вы, как сервер, возможно, прокси-сервер, получаете запрос от клиента, затем начинаете действовать по нему (или ретранслируете запрос вышестоящему серверу), и до того, как вы подготовили ответ, клиент решает отменить/прервать запрос.

Эта трассировка стека показывает, что происходит, когда клиент отменяет запрос.

Trace: { [Error: socket hang up] code: 'ECONNRESET' }
    at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
    at ClientRequest.emit (events.js:117:20)
    at Socket.socketCloseListener (http.js:1526:9)
    at Socket.emit (events.js:95:17)
    at TCP.close (net.js:465:12)

линия http.js:1526:9указывает на то же самое socketCloseListener упоминается @Blender, в частности:

// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());

...

function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;
}

Это типичный случай, если клиент является пользователем в браузере. Запрос на загрузку какого-либо ресурса/страницы занимает много времени, и пользователи просто обновляют страницу. Такое действие приводит к прерыванию предыдущего запроса, что на стороне вашего сервера вызывает эту ошибку.

Поскольку эта ошибка вызвана желанием клиента, он не ожидает получить какое-либо сообщение об ошибке. Так что не стоит считать эту ошибку критической. Просто игнорируйте это. Этому способствует тот факт, что при такой ошибке res сокет, который слушал ваш клиент, хотя и доступен для записи, но уничтожен.

console.log(res.socket.destroyed); //true

Итак, нет смысла отправлять что-либо, кроме явного закрытия объекта ответа:

res.end();

Однако то, что вы следует сделать конечно, если вы Он прокси-сервер, который уже передал запрос восходящему потоку, должен прервать ваш внутренний запрос к восходящему, указывая на ваше отсутствие интереса к ответу, что, в свою очередь, скажет вышестоящему серверу, возможно, остановить дорогостоящую операцию.

Понравилась статья? Поделить с друзьями:
  • Request error read econnreset радмир
  • Request error getaddrinfo radmir
  • Request error getaddrinfo enotfound
  • Request error character name is wrong перевод
  • Request does not match any route pocketbook как исправить