Доброго времени суток!
Время от времени ловлю в логах приложения такую бяку:
Есть идеи как вычислить виновника катастрофы и/или не вылетать с критической ошибкой?
3 ответа 3
Не вылетать с критической ошибкой можно с помощью
Но надо учесть, что критические ошибки потому и критические, что после них с некоторой вероятностью некоторые вещи перестанут работать. Поэтому всё же стоит добавить в обработчик нечто вроде
socket hang up не является фатальной ошибкой и не кидается в качестве исключения.
Возможно это ошибка клиента. Также здесь сказано что если сокет недоступен для записи, он немедленно уничтожается, поэтому в данном случае виновника найти не удастся. Иногда это происходит по причине отсутствия поддержки какого нибудь звена на стороне клиента (к сожалению не могу точно сказать чего, пока сам изучаю). В таком случае сервер с клиентом договариваются между собой о новом соединении, которое поддерживают обе стороны. И в случае удачного соединения, сокет клиента придет уже с другим портом.
Вот пример, в котором я отсылаю заброс на API-интерфейс с помощью Postman используя SSL / TLS соединение и необходимого сертификата.
Из этого лог-файла можно увидеть что произошло два соединения. Но прежде чем ошибка успела отработать, сокет уже был уничтожен и подсоединен с другого порта. А две подстроки с текстом undefined свидетельствуют о том, что сокета уже не существует.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками node.js или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.11.23.40809
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Я создаю веб-скребок с Node и Cheerio, и для определенного веб-сайта я получаю следующую ошибку (это происходит только на этом одном веб-сайте, а не на других, которые я пытаюсь очистить).
Это происходит каждый раз в другом месте, поэтому иногда url x возникает ошибка, в других случаях url x это нормально, и это совершенно другой URL:
Я не могу найти объяснение этому нигде!
РЕДАКТИРОВАТЬ: Вот пример кода, который (иногда) возвращает ошибки:
Прямого вызова для закрытия соединения нет, но я использую Node Request который (насколько я могу судить) использует, http.get так что это не требуется, поправьте меня, если я ошибаюсь!
РЕДАКТИРОВАТЬ 2: Вот фактический, используемый бит кода, который вызывает ошибки. prodURL и другие переменные в основном являются селекторами jquery, которые определены ранее. Это использует async библиотеку для узла.
Есть два случая, когда socket hang up бросают:
Когда вы клиент
Когда вы, как клиент, отправляете запрос на удаленный сервер и не получаете своевременного ответа. Ваш сокет закончен, который выдает эту ошибку. Вам нужно перехватить эту ошибку и решить, как ее обработать: повторить ли запрос, поставить его в очередь на потом и т. Д.
Когда вы сервер / прокси
Когда вы, как сервер, возможно, прокси-сервер, получаете запрос от клиента, затем начинаете действовать на него (или передаете запрос на вышестоящий сервер), и, прежде чем вы подготовите ответ, клиент решает отменить / отменить запрос.
Эта трассировка стека показывает, что происходит, когда клиент отменяет запрос.
Линия http.js:1526:9 указывает на то же самое, socketCloseListener упомянутое выше @Blender, в частности:
Это типичный случай, если клиент является пользователем в браузере. Запрос на загрузку какого-либо ресурса / страницы занимает много времени, и пользователи просто обновляют страницу. Такое действие приводит к прерыванию предыдущего запроса, который на вашей стороне сервера выдает эту ошибку.
Поскольку эта ошибка вызвана желанием клиента, он не ожидает получения какого-либо сообщения об ошибке. Таким образом, нет необходимости рассматривать эту ошибку как критическую. Просто игнорируй это. Это подтверждается тем фактом, что при такой ошибке res сокет, который слушал ваш клиент, хотя и остается доступным для записи, разрушается.
Таким образом, нет смысла отправлять что-либо, кроме явного закрытия объекта ответа:
Postman : socket hang up
I just started using Postman. I had this error «Error: socket hang up» when I was executing a collection runner. I’ve read a few post regarding socket hang up and it mention about sending a request and there’s no response from the server side and probably timeout. How do I extend the length of time of the request in Postman Collection Runner?
16 Answers 16
Socket hang up, error is port related error. I am sharing my experience. When you use same port for connecting database, which port is already in use for other service, then «Socket Hang up» error comes out.
eg:- port 6455 is dedicated port for some other service or connection. You cannot use same port (6455) for making a database connection on same server.
Sometimes, this error rises when a client waits for a response for a very long time. This can be resolved using the 202 (Accepted) Http code. This basically means that you will tell the server to start the job you want it to do, and then, every some-time-period check if it has finished the job.
If you are the one who wrote the server, this is relatively easy to implement. If not, check the documentation of the server you’re using.
Postman was giving «Could not get response» «Error: socket hang up». I solved this problem by adding the Content-Length http header to my request
Are you using nodemon, or some other file-watcher? In my case, I was generating some local files, uploading them, then sending the URL back to my user. Unfortunately nodemon would see the «changes» to the project, and trigger a restart before a response was sent. I ignored the build directories from my file-watcher and solved this issue.
I have just faced the same problem and I fixed it by close my VPN. So I guess that’s a network agent problem. You can check if you have some network proxy is on.
Socket hang up error could be due to the wrong URL of the API you are trying to access in the postman. please check the URL once carefully.
I solved this problem with disconnection my vpn. you should check if there is vpn connected.
this happaned when client wait for response for long time try to sync your API requests from postman
then make login post and your are done
«socket hang up» is proxy related issue. when we run same collection with the help of newman on jenkins then all test are passed. change the proxy setting https://docs.cloudfoundry.org/cf-cli/http-proxy.html
If Postman doesn’t get response within a specified time it will throw the error «socket hang up».
I was doing something like below to achieve 60 minutes of delay between each scenario in a collection:
I reduced time duration to 30 seconds:
After that I stopped getting this error.
I had the same issue: «Error: socket hang up» when sending a request to store a file and backend logs mentioned a timeout as you described. In my case I was using mongoDB and the real problem was my collection’s array capacity was full. When I cleared the documents in that collection the error was dismissed. Hope this will help someone who faces a similar scenario.
It’s possible there are 2 things, happening at the same time.
I had this problem. My server port was 45860 and I was using pSiphon anti-filter VPN. In that condition my Postman reported «connection hang-up» only when server’s reply was an error with status codes bigger than 0. (It was fine when some text was returning from server with no error code.)
When I changed my web service port to 8080 on my server, WOW, it worked! even though pSiphon VPN was connected.
Hang in There! (A solution to socket hang up)
Nov 12, 2019 · 5 min read
Recently, while watching a YouTube video about how to create a Node.js backend (Building a RESTful API with Node.js by Academind), I encountered an error that for the life of me I could not figure out. This blog post will go over my process of solving the error and what the actual (and surprisingly/annoyingly) simple solution was.
First thing to note is, I was building this backend by following a step by step instructional video which incorporated MongoDB to host the database and Postman to display it. This means that by following the instructions to a T, I should have no issues. So why did my whole thing crash? Well, it didn’t. Not really. Actually, what crashed was Postman. I would get the error message “socket hang up”.
Looking at that list of possibilities, 75% of them point to the issue being something to do with the setup of Postman, so I figured since the video was a few years old, perhaps Postman had since updated and the video no longer showed the proper setup. So, I set about playing with the settings to varying degrees of nothing. It was frustrating, but undeterred I moved on to the next potential point of error.
Checking the list of potential error points again, I saw that the possibly my backend was not working properly. I concluded this must mean that MongoDB must be where the issue lied. I then proceeded to attempt to rebuild and my setup (about 4 times) with no change. I even went into the setting and tried messing with the IP addresses in hopes something would work. Still no luck.
Giving up on figuring it out on my own, I turned to my peers online, and tried resources such as stackoverflow.com to see if anyone else had encountered this error. To my joy, many had. However, to my disappointment, they all had different potential solutions to how to solve it. The most common solution suggested, seemed to think setting a setTimeOut() on the request function would solve the problem. I didn’t think that was the answer I was looking for. This would suggest that the database was too large to properly shift though. I was just trying to do a simple POST request in Postman with these parameters:
There should be no reason why it should take longer than a second to fetch. So that nixed that solution.
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 different location every time, so sometimes it’s url x that throws the error, other times url x is fine and it’s a different url entirely:
This is very tricky to debug, I don’t really know where to start. To begin, what IS a socket hang up error? Is it a 404 error or similar? Or does it just mean that the server refused a connection?
I can’t find an explanation of this anywhere!
EDIT: Here’s a sample of code that is (sometimes) returning errors:
There is no direct call to close the connection, but I’m using Node Request which (as far as I can tell) uses http.get so this is not required, correct me if I’m wrong!
EDIT 2: Here’s an actual, in-use bit of code that is causing errors. prodURL and other variables are mostly jquery selectors that are defined earlier. This uses the async library for Node.
29 Answers 29
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.
Line http.js:1526:9 points to the same socketCloseListener mentioned by @Blender, particularly:
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.
So, no point to send anything, except explicitly closing the response object:
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.









