0

I am catching errors from an Ajax response. The kind of error that comes back depends on where it was thrown and I need to look out for certain ones.

I know the error variable always exists but past this I have to check the existence for each level, otherwise risk getting a TypeError: Cannot read property '0' of undefined error.

I am currently doing:

if (error.response && error.response.data && error.response.data.errors 
&& error.response.data.errors[0].title === 'no_space') {
   //do something
}

But there must be a better way?

3
  • 2
    just add another && error.response.data.errors[0] && ... Commented Nov 1, 2018 at 11:07
  • 1
    I think what you are looking for could be coming soon - optional chaining - dev.to/sammyisa/… Commented Nov 1, 2018 at 11:10
  • “But there must be a better way?” - why is this so convoluted in the first place? If you are in charge of the script that generates this structure in the first place, I’d maybe start by simplifying things there. error.response.data.errors seems rather redundant to begin with. Commented Nov 1, 2018 at 12:39

1 Answer 1

1

You could reduce the keys and take the final value for a check.

var keys = ['response', 'data', 'errors', 0, 'title'];
if (keys.reduce((o, k) => (o || {})[k], error) === 'no_space') {
    // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I assume for this to work I would always need to know all the keys to get to the final value?
right, you need to know all keys in advance. what use case do you have?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.