2

Let's say I have a Promise and catch the error like so:

fetch().then(data => {
  console.log(data);
}).catch(console.error);

Is this a valid code? I've seen people do this, but I don't understand how catch(console.error) works.

1
  • 1
    Why wouldn't it work? Notice how you can simplify to fetch().then(console.log).catch(console.error); or just fetch().then(console.log, console.error);
    – Bergi
    Nov 28, 2021 at 6:26

2 Answers 2

4

Yes, if you just want to log the error and otherwise ignore it, that works.

.catch expects you to pass it in a function, and if the promise rejects, that function will be called with the rejection value. Often you'll create a new function with custom logic and pass that in, but it's fine to pass in a function that already exists, such as console.error.

2

yes it's all right.It's same as passing error object and then logging it in console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.