elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

retry middleware swallows errors #141

Closed dxptqhtlutehvlyxcmtg closed 2 years ago

dxptqhtlutehvlyxcmtg commented 2 years ago

Thanks for this incredibly useful library.

After the retry middleware eventually exceeds maxAttempts, the intended error helper method is never called.

import wretch from "wretch";
import { retry } from "wretch/middlewares/retry";

console.log("Fetching...");

wretch("https://httpstat.us")
  .middlewares([retry({ maxAttempts: 2 })])
  .get("/503")
  .error(503, (e) => {
    // this is never called
    console.log("Received 503 error");
  })
  .res((response) => {
    console.log(response);
  });

Sandbox of above

Instead we encounter a "Number of attempts exceeded" exception which seemingly lacks the most recent response or any details of the underlying request failure.

elbywan commented 2 years ago

Hey @dxptqhtlutehvlyxcmtg,

Thanks for this incredibly useful library.

Thanks a bunch! 🙇

After the retry middleware eventually exceeds maxAttempts, the intended error helper method is never called. Instead we encounter a "Number of attempts exceeded" exception which seemingly lacks the most recent response or any details of the underlying request failure.

I agree, it can be very useful to process the latest attempt instead of throwing an error.

I just added a flag which makes this possible (when enabled).

wretch("https://httpstat.us")
    .middlewares([retry({ maxAttempts: 2, resolveWithLatestResponse: true })])
    .get("/503")
    .error(503, (e) => {
      console.log("Received 503 error");
    })
    .res((response) => {
      console.log(response);
    });

// => Received 503 error
dxptqhtlutehvlyxcmtg commented 2 years ago

This works great. Very much appreciated, thank you.