Skip to content

Connection errors are not handled in client.query unless on('error') is defined. #2191

@joras

Description

@joras

Expected behaviour from documentation:

  • if connection error happens during client.query() a error should be thrown(or callback error)
  • if connection error happens when no queries are running(connection idle), on('error') should be emitted.

Actual behaviour:

  • if connection error happens during client.query() and client.on('error') is not attached, no error is returned from query() and since on('error') is missing a process gets unhandledException and probably dies
  • if connection error happens during client.query() and client.on('error') is attached, client.query() throws error correctly.

This only applies to connection erros, SQL errors are always thrown.

you can play with it with following code: if let it run, you see invalid query errors are caught, but if you stop postgres, it query() does not throw, and due to unhandled error process dies. But if you uncomment on('error') handler, a error is handled in the event handler, and query() correctly

import { Client } from "pg";

async function main() {
  const client = new Client({
    host: "localhost",
    port: 5432,
    user: "postgres",
    password: "postgres",
    database: "test",
  });

  await client.connect();
  //  client.on("error", (err) => console.error("connection error", err));

  while (true) {
    try {
      console.log(await client.query("SELECT pg_sleep(5)"));
    } catch (e) {
      console.log("caught error", e);
    }
    try {
      console.log(await client.query("SELECT asdf"));
    } catch (e) {
      console.log("caught error", e);
    }
  }
}

main().catch((err) => {
  console.error("main error", err);
});```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions