While working on a solution to manage cookies in JS, I encountered an issue. The cookies I am dealing with can have content in JSON format, like so:
var cookieContents = '{"type":"cookie","isLie":true}';
... or they could simply be plain strings:
var cookieContents = 'The cookie is a lie';
When trying to parse the cookie using JSON.parse(cookieContents)
, I realized that JSON.parse()
cannot handle plain strings and throws a fatal error.
So, my question is: What is the most widely accepted approach to handle this situation?
I attempted to use a try/catch block:
var cookie1 = '{"type":"cookie","isLie":true}';
var cookie2 = 'The cookie is a lie';
function parseCookieString(str){
var output;
try{
output = JSON.parse(str);
} catch(e){
output = str;
}
console.log(output);
}
parseCookieString(cookie1); // outputs object
parseCookieString(cookie2); // outputs string
You can view the code in action here: http://jsfiddle.net/fmpeyton/7w60cesp/
Although this method works well, it feels somewhat makeshift. I typically do not handle fatal errors in JavaScript. Is it common practice to address these errors more elegantly in such scenarios?