English

Node.jsでsocket hang upが出たときの直し方

​​Node.js​JavaScript,トラブルシュート

Node.js の http.request で Error: socket hang up(code は ECONNRESET)が出たら、応答が返ってくる前に接続が切れています。まず、接続先のサーバーで何が起きたかをログで確かめます。同じ状況で fetch() を使うと、メッセージは TypeError: fetch failed になり、その cause に other side closed と出ます。

Node.js のスクリプトや API サーバーから別の API サーバーに HTTP リクエストを送り、このエラーで処理が止まったときに役立つ内容です。検証環境で、送られてきた JSON が壊れていると落ちるサーバーを作ってエラーを起こし、サーバーを直すとエラーが消えることを確かめました。

補足

検証環境は Ubuntu 24.04、Node.js 22.23.5、curl 8.5.0 です。クライアントもサーバーも同じマシンで動かしました。HTTPS、プロキシやロードバランサーを挟んだ構成、keep-alive で使い回している接続が切れる場合、Windows と macOS、Node.js 21 以前では試していません。

サーバーが落ちたときに出るメッセージ

検証用に、受け取った本文を JSON.parse して返すだけのサーバー server.mjs を用意しました。本文が JSON として正しくないと、JSON.parse が例外を投げ、それを受け止める処理がないのでプロセスごと終了します。

js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => {
    const data = JSON.parse(body);
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ received: data }));
  });
});

server.listen(3000, () => {
  console.log('http://localhost:3000 で待ち受けています');
});

クライアントの client-http.mjs は、node:http の request で、末尾に余分なカンマがある JSON を POST します。

js
import { request } from 'node:http';

const req = request('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
}, (res) => {
  let text = '';
  res.on('data', (chunk) => { text += chunk; });
  res.on('end', () => console.log(res.statusCode, text));
});
req.end('{"name": "neko",}');

サーバーを起動しておき、node client-http.mjs を実行すると、次のように出て終了コード 1 で終わりました。

text
node:events:497
      throw er; // Unhandled 'error' event
      ^

Error: socket hang up
    at Socket.socketOnEnd (node:_http_client:599:25)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21)
Emitted 'error' event on ClientRequest instance at:
    at emitErrorEvent (node:_http_client:108:11)
    at Socket.socketOnEnd (node:_http_client:599:5)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
  code: 'ECONNRESET'
}

Node.js v22.23.5

Node.js のドキュメントにある http.request の説明には、応答を受け取る前に接続が途中で閉じられると、Error: socket hang up というメッセージで code が ECONNRESET の 'error' イベントが出る、と書かれています。上の出力はこのとおりです。

1行目の Unhandled 'error' event は、req に 'error' のリスナーを付けていないことを示しています。events のドキュメントによると、リスナーのない 'error' イベントが出ると、エラーが投げられ、スタックトレースを表示してプロセスが終了します。クライアントのスクリプトが止まったのは、このためです。

fetch では「other side closed」と出る

同じサーバーに、fetch() で同じ本文を送る client-fetch.mjs も試しました。

js
const res = await fetch('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: '{"name": "neko",}',
});
console.log(res.status, await res.text());

こちらは socket hang up という言葉は出ず、TypeError: fetch failed の下の [cause] に SocketError: other side closed(相手の側が閉じた)と出ました。終了コードは 1 です(パスは例示用の値に置き換えています)。

text
node:internal/deps/undici/undici:15456
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:15456:13
    at async file:///path/to/app/client-fetch.mjs:1:13 {
  [cause]: SocketError: other side closed
      at Socket.<anonymous> (node:internal/deps/undici/undici:6569:28)
      at Socket.emit (node:events:531:35)
      at endReadableNT (node:internal/streams/readable:1698:12)
      at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
    code: 'UND_ERR_SOCKET',
    socket: {
      localAddress: '127.0.0.1',
      localPort: 42962,
      remoteAddress: '127.0.0.1',
      remotePort: 3000,
      remoteFamily: 'IPv4',
      timeout: undefined,
      bytesWritten: 248,
      bytesRead: 0
    },
    [Symbol(undici.error.UND_ERR)]: true,
    [Symbol(undici.error.UND_ERR_SOCKET)]: true
  }
}

Node.js v22.23.5

Node.js の fetch は、node:http ではなく undici という HTTP クライアントをもとに作られています(Node.js のドキュメントにある fetch の説明)。そのため、同じ原因でもメッセージの言葉が変わります。socket に添えられたソケットの情報のうち、bytesRead: 0 は、サーバーから受け取ったバイト数が 0 だったことを表しています(net のドキュメントにある socket.bytesRead の説明)。応答を1バイトも受け取らないうちに、接続が切れていました。

原因はサーバーのログに出ている

クライアントのエラーは、接続が切れたことしか伝えません。なぜ切れたのかは、サーバーの側を見ないと分かりません。検証では、サーバーの出力に次のスタックトレースが残っていて、サーバーのプロセスは終了コード 1 で終わっていました(パスは例示用の値に置き換えています)。

text
http://localhost:3000 で待ち受けています
<anonymous_script>:1
{"name": "neko",}
                ^

SyntaxError: Expected double-quoted property name in JSON at position 16 (line 1 column 17)
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (file:///path/to/app/server.mjs:7:23)
    at IncomingMessage.emit (node:events:519:28)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21)

Node.js v22.23.5

server.mjs の7行目の JSON.parse が、neko", のあとのカンマで失敗しています。process のドキュメントのとおり、受け止められなかった例外は、スタックトレースを表示してプロセスを終了させます。プロセスが終わると接続も閉じられるので、応答を待っていたクライアントの側では socket hang up になります。

Node.js を通さずに curl で同じ本文を送っても、応答は返りませんでした。

console
$ curl -sS -X POST -H 'Content-Type: application/json' -d '{"name": "neko",}' http://localhost:3000/api/items
curl: (52) Empty reply from server

libcurl のエラーコードの一覧では、52 は、サーバーから何も返ってこなかったことを表すエラーです。curl でも同じなら、クライアントのコードではなくサーバーの側で接続が切られている、と切り分けられます。

サーバーで例外を受け止めて、エラーの応答を返す

直すのはサーバーです。JSON.parse を try/catch で囲み、失敗したときはプロセスを落とさずに、ステータスコード 400 の応答を返すようにしました(server-fixed.mjs)。

js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => {
    let data;
    try {
      data = JSON.parse(body);
    } catch {
      res.statusCode = 400;
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ error: 'JSON の形が正しくありません' }));
      return;
    }
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ received: data }));
  });
});

server.listen(3000, () => {
  console.log('http://localhost:3000 で待ち受けています');
});

このサーバーに向けて、先ほどと同じ client-http.mjs と client-fetch.mjs を実行すると、どちらもエラーは出ず、400 の応答が表示されて終了コード 0 で終わりました。

console
$ node client-http.mjs
400 {"error":"JSON の形が正しくありません"}
$ node client-fetch.mjs
400 {"error":"JSON の形が正しくありません"}

サーバーの出力は起動時の1行だけで、クライアントを続けて実行したあとも、サーバーは動き続けていました。

クライアントでもエラーを受け取っておく

接続先が自分では直せない外部のサーバーの場合もあります。そのときでもスクリプトが長いスタックトレースで止まらないように、req に 'error' のリスナーを付けておきます(client-http-handled.mjs)。

js
import { request } from 'node:http';

const req = request('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
}, (res) => {
  let text = '';
  res.on('data', (chunk) => { text += chunk; });
  res.on('end', () => console.log(res.statusCode, text));
});
req.on('error', (err) => {
  console.error(`リクエストに失敗しました: ${err.message}(${err.code})`);
  process.exitCode = 1;
});
req.end('{"name": "neko",}');

落ちるほうのサーバー(server.mjs)に送ると、次の1行が出て、終了コード 1 で終わりました。

console
$ node client-http-handled.mjs
リクエストに失敗しました: socket hang up(ECONNRESET)

直したサーバーに送ったときは、400 {"error":"JSON の形が正しくありません"} と表示され、終了コード 0 でした。

自分でタイムアウトさせたときも同じメッセージになる

接続を切ったのが相手ではなく、自分のコードということもあります。http.request の timeout オプションは、通信がないまま指定した時間が過ぎると 'timeout' イベントを出すだけで、リクエストは自分で止める必要があります(http.request の 'timeout' イベントの説明)。そこで req.destroy() を呼ぶと、応答の前に接続を閉じたことになり、やはり socket hang up が出ます。

3秒後に応答するサーバー(server-slow.mjs)に向けて、1秒でタイムアウトする次の client-timeout.mjs を実行しました。

js
import { request } from 'node:http';

const req = request('http://localhost:3000/', { timeout: 1000 }, (res) => {
  res.resume();
  res.on('end', () => console.log(res.statusCode));
});
req.on('timeout', () => {
  req.destroy();
});
req.on('error', (err) => {
  console.error(`${err.message}(code: ${err.code ?? "なし"})`);
});
req.end();
console
$ node client-timeout.mjs
socket hang up(code: ECONNRESET)

これでは、相手が切ったのか、自分で打ち切ったのかが、メッセージからは区別できません。http.request の説明には、接続が成立する前に req.destroy() を呼んだ場合、socket hang up か、req.destroy() に渡したエラーが 'error' イベントに届くと書かれています。今回のように応答を待っている途中で打ち切る場合について、'timeout' のリスナーを次のように変えて試したところ、socket hang up の代わりに、渡したエラーのメッセージが表示されました。

js
req.on('timeout', () => {
  req.destroy(new Error('1秒以内に応答がなかったので打ち切りました'));
});
console
$ node client-timeout-fixed.mjs
1秒以内に応答がなかったので打ち切りました(code: なし)

fetch でタイムアウトさせたいときは、AbortSignal.timeout() を signal に渡します。同じサーバーに向けて fetch('http://localhost:3000/', { signal: AbortSignal.timeout(1000) }) を実行し、catch で受け取ったエラーを console.error(`${err.name}: ${err.message}`) で表示すると、次のように出ました。

text
TimeoutError: The operation was aborted due to timeout

名前が TimeoutError なので、接続が切られたエラーと見分けられます(MDN の AbortSignal.timeout() の説明)。

​Posted by 86