sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

beforeError hook isn't called on 500 responses

geoff-harper opened this issue · comments

Hey I've encountered an issue when receiving 500 server codes from an api. For whatever reason it doesn't seem like the beforeError hook gets called. The following instance isn't producing any logs in the console when I hit a 500.

const api = ky.create({
    retry: 0,
    hooks: {
      beforeError: [
        (error) => {
          console.log('handleBeforeServerError');
        },
      ],
    },
  });
};

I've confirmed that the same code is fine for 404s and other 400 codes. Here are the raw response headers for the 500

HTTP/2 500 
date: Wed, 17 Apr 2024 16:04:41 GMT
content-length: 0
strict-transport-security: max-age=31536000; includeSubDomains
X-Firefox-Spdy: h2

and the 404

HTTP/2 404 
date: Wed, 17 Apr 2024 16:05:52 GMT
content-length: 0
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
vary: Origin
strict-transport-security: max-age=31536000; includeSubDomains
X-Firefox-Spdy: h2

Does 404 work? What environment are you running in? Native Fetch or node-fetch?

We have a test to confirm it's working:

ky/test/hooks.ts

Lines 610 to 640 in 2d56baf

test('runs beforeError before throwing HTTPError', async t => {
const server = await createHttpTestServer();
server.post('/', (_request, response) => {
response.status(500).send();
});
await t.throwsAsync(
ky.post(server.url, {
hooks: {
beforeError: [
(error: HTTPError) => {
const {response} = error;
if (response?.body) {
error.name = 'GitHubError';
error.message = `${response.statusText} --- (${response.status})`.trim();
}
return error;
},
],
},
}),
{
name: 'GitHubError',
message: 'Internal Server Error --- (500)',
},
);
await server.close();
});

It's in native fetch and 404 is working. I can't imagine it would make a difference but I'm noticing it on a PUT req. I've also checked it on Firefox and Chrome. Its options req is 200, I can't remember if it's the same outcome when an options req is 500