Skip to content

onError hook not triggered for network errors (ECONNREFUSED, DNS failures, etc.) #75

@leo91000

Description

@leo91000

Description

The onError hook is not triggered when a network-level error occurs (e.g., ECONNREFUSED, DNS failures, timeout at network level). Instead, the error is thrown as an uncaught exception.

This is inconsistent with the behavior for HTTP errors (4xx, 5xx), where onError is properly called and the error is returned as { data: null, error: ... }.

Expected Behavior

Network errors should:

  1. Trigger the onError hook
  2. Return { data: null, error: ... } (consistent with HTTP errors)
  3. NOT throw an exception (unless throw: true is set)

Actual Behavior

Network errors:

  1. Do NOT trigger the onError hook
  2. Throw an uncaught TypeError: fetch failed exception
  3. Break the error-as-value pattern

Minimal Reproduction

import { createFetch } from "@better-fetch/fetch";

let onErrorCalled = false;

const $fetch = createFetch({
  baseURL: "http://localhost:9999", // non-existent server
  onError(context) {
    onErrorCalled = true;
    console.log("onError triggered:", context.error);
  },
});

try {
  const { data, error } = await $fetch("/test");
  console.log("Result:", { data, error, onErrorCalled });
} catch (e) {
  console.log("Exception thrown:", e.message);
  console.log("onError was called:", onErrorCalled);
}

Output:

Exception thrown: fetch failed
onError was called: false

Environment

  • @better-fetch/fetch: 1.1.21
  • Node.js: 22.14.0
  • OS: Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions