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);
>Solution :
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.
// First you want to represent your err as a JSON object
var err = '{ "error": { "code": "card_declined", ///.../// "type": "card_error" } }';
// Now you can parse it
let obj = JSON.parse(err);
console.log(obj.error.decline_code); // Output: insufficient_funds
In addition if you want to keep your error structure you can do something like this:
const errIntro = 'Your card is declined due to '
console.log(errIntro + obj.error.decline_code); //Output: Your card is declined due to insufficient_funds
If you want a clearer answer you can even remove the ‘_’ and you can also add a nice final point using:
const errorCode = obj.error.decline_code.replace(/_/g, ' ');
console.log(errIntro + errorCode + '.'); //Output: Your card is declined due to insufficient funds.
I hope it helps. 🙂