0

I have come up with a solution is there is any better approach to solve this in JavaScript

if (error.response && error.response.data && error.response.data.error) {
  console.log(error.response.data.error);
} else {
  console.log('Sorry, Something went wrong!');
}
VnoitKumar
  • 1,350
  • 15
  • 29

1 Answers1

0

For now, that's how you do it.

At some point, the optional chaining proposal may progress. Using the syntax from that proposal, you'd be able to write this:

// NOT VALID SYNTAX YET (A STAGE 2 PROPOSAL)
if (error.response?.data?.error) {
  console.log(error.response.data.error);
} else {
  console.log('Sorry, Something went wrong!');
}

You can use that syntax today if you transpile with Babel and use the @babel/plugin-proposal-optional-chaining plugin.

Live Example on Babel's REPL

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875