0

Small JS question. I have the following code in report function:

this.httpClient(reqConfig).catch(function (error) {
    console.log("here");
    return new Error('Failed with' + error);
});

How can I make return Error in report? As I understand, currently it just return Error in catch and then it continue running in report.

2
  • throw new Error(); Commented Dec 8, 2020 at 11:32
  • 1
    Please post the entire report function you're talking about. Does it return a promise? Commented Dec 8, 2020 at 11:34

2 Answers 2

1

To make the promise catch returns reject, you need to either throw the error or return a rejected promise:

throw new Error('Failed with ' + error);

or

return Promise.reject(new Error('Failed with ' + error));

Then to have report report (as it were) that error, it has to return the promise returned by catch, or return another promise that is resolved to the promise from catch. For instance, if report is an async function, await the result from catch. If it isn't, return that result:

return this.httpClient(reqConfig).catch(function (error) {
    console.log("here");t
    throw new Error('Failed with' + error);
});

For clarity: You can't make report throw an error from within that catch callback, because report has already returned before that callback runs. (Though if report is an async function, you can write your logic as though it were really throwing the error.)

Sign up to request clarification or add additional context in comments.

2 Comments

I want the code to continue running if this.httpClient didn't faild. How can I do it?
@vesii - If report is not an async function, attach a fulfillment handler using .then. if it is, use await. It's hard to be more specific with only the information in the question. See developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… (or Chapters 8 and 9 of my recent book JavaScript: The New Toys, links in my profile if you're interested ;-) ).
0

Currently you are just returning an error object. To throw an exception use the throw keyword:

this.httpClient(reqConfig).catch(function (error) {
    console.log("here");
    throw 'Failed with' + error
});

If you just want to log the error use console.error():

this.httpClient(reqConfig).catch(function (error) {
    console.log("here");
    console.error('Failed with' + error)
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.