elbywan/wretch

Timeout and catch it

jaclas opened this issue · 3 comments

jaclas commented

In Node 18, is it necessary to use polyfilly for AboreController to use the setTiemout() controller?

According to the compatibility table https://developer.mozilla.org/en-US/docs/Web/API/AbortController support is from Node 15.

It partially works, because I get an exception from AbortController in the log, but I don't get anything in the timeout() event:

    try {
        response = await api.url(endpoint)
            .get()
            .setTimeout(1000)
            .timeout(err => console.log("timeout!!!: ", err.status))  <=== this is not running
            .res(async response => {
                response.headers.forEach((value, key) => {
                    headers[key] = value;
                });
                const res = {
                    status: response.status,
                    statusText: response.statusText,
                    ok: response.status > 199 && response.status < 400 ? true : false,
                    data: await response.json()
                };

                return res;
            });
    } catch (error) {
        console.log("    Get ERROR ");
        console.log(error);
        response = {
            ok : false,
            url: error.url,
            status: error.status,
            statusText: error.statusText
        };
    }

How can i correct this behaviour?

Hey @jaclas,

In Node 18, is it necessary to use polyfilly for AboreController to use the setTiemout() controller?

Normally it should work without the polyfill.

.timeout(err => console.log("timeout!!!: ", err.status)) <=== this is not running

I think the issues comes from the fact that the .timeout method catches the 408 http code, not when an abort controller aborts a request.

Could you try using .onAbort instead?

jaclas commented

Yes, onAbort() works. Thanks.
And as I understand this event is the last in the chain, and here I should handle the error and return the error information to be passed outside?

Yes, onAbort() works. Thanks.

Cool :).

And as I understand this event is the last in the chain, and here I should handle the error and return the error information to be passed outside?

Yes onAbort accepts a callback that will be called when the request gets aborted - for instance when the timeout triggers. Inside the callback you can process the error, extract the data you want and return it.

// response will be either the value returned from `.res` or `.onAbort`
response = await api
  .url(endpoint)
  .get()
  .setTimeout(1000)
  .onAbort((err) => {
     // process the error here
  })
  .res(async (response) => {
    // regular case when there is no error thrown
  });