0

I have a promise:

  return this.credentialFetch(url.href, {
            method: 'get',
            signal: abort.signal,
            headers: jsonHeaders,
        })
            .then((res) => {
                if (res.ok) return res.json();
            })
            .catch(catchRequestError(res, this.globalService));

And function that is called when error occurs:

export function catchRequestError<T>(result: T, globalService: GlobalService) {
    globalService.emitHttpResponse(result);
}

I get this error:

Argument of type 'void' is not assignable to parameter of type '(reason: any) => PromiseLike<never>'.

On the line:

.catch(catchRequestError(res, this.globalService));

How to handle promise error?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 1
    `.catch(catchRequestError(res, this.globalService));` **calls** `catchRequestError` and then passes its return value into `catch`, exactly the way `foo(bar())` **calls** `bar` and passes its return value to `foo`. To have `catchRequestError` get called if the promise rejects, pass a *function* into `catch` that will call it, e.g. `.catch(() => catchRequestError(res, this.globalService));` – T.J. Crowder Jun 26 '21 at 12:57
  • Okay, but in place where I expect data I expect specific type not error: `let layersPolygons = await this.update();` in `layersPolygons` –  Jun 26 '21 at 13:14
  • in error case it return void, but I expect data –  Jun 26 '21 at 13:16
  • 1
    Then you're handling errors at the wrong level. In general, you want to return the promise chain *without* using `catch` so that errors follow the chain. You only use `catch` at the topmost level. This is a **lot** easier when you use `async` functions and `await` rather than using `.then` and `.catch`, because the propagation happens automatically. For instance, your code above would be much simpler in an `async` function: https://pastebin.com/SmXAeFFH (I've assumed you want the function to reject when `res.ok` is false). – T.J. Crowder Jun 26 '21 at 13:23

0 Answers0