I have an error message like following
Your card is declined due to "{n "error": {n "code": "card_declined",n "decline_code": "insufficient_funds",n "doc_url": "https://stripe.com/docs/error-codes/card-declined",n "message": "Your card has insufficient funds.",n "param": "",n "request_log_url": "https://dashboard.stripe.com/test/logs/req_fhgKiF9C0d1RrK?t=1700727296",n "type": "card_error"n }n}n"
I want to fetch the value of decline_code
that is insufficient_funds
.
I am trying the below code. It gives me an error like
Bug in custom code TypeError: Cannot read properties of undefined (reading ‘decline_code’)
can you help me finding he solution as i dont know the javascript just trying from the different stackoverflow posts.
var err = Your card is declined due to "{n "error": {n "code": "card_declined",n "decline_code": "insufficient_funds",n "doc_url": "https://stripe.com/docs/error-codes/card-declined",n "message": "Your card has insufficient funds.",n "param": "",n "request_log_url": "https://dashboard.stripe.com/test/logs/req_fhgKiF9C0d1RrK?t=1700727296",n "type": "card_error"n }n}n";
let obj = JSON.parse(err);
return (obj.error.decline_code);
3
Answers
You need to parse the JSON so it needs to be valid
If it is impossible to fix this on the server (which it should) then you can do
Since your string both contains normal text and json that needs to be parsed you could do something like this:
Your getting error beacause JSON.parse parses only jsons. Your err is nor a json because of the ‘ Your card is declined due to ‘ section.
In addition if you want to keep your error structure you can do something like this:
If you want a clearer answer you can even remove the ‘_’ and you can also add a nice final point using:
I hope it helps. 🙂