[英]Handling exception from unparsable input into JSON.parse()
I came across this issue while creating a way to manage cookies in JS. 我在创建一种在JS中管理cookie的方法时遇到了这个问题。 My cookies can contain strings that are in JSON format:
我的Cookie可以包含JSON格式的字符串:
var cookieContents = '{"type":"cookie","isLie":true}';
... or that are just plain strings: ...或者仅仅是纯字符串:
var cookieContents = 'The cookie is a lie';
To parse the cookie, I would ideally do JSON.parse(cookieContents)
. 要解析cookie,理想情况下,我将执行
JSON.parse(cookieContents)
。 The problem with this is JSON.parse()
cannot parse a plain string and throws a fatal error. 这样做的问题是
JSON.parse()
无法解析纯字符串并引发致命错误。
My question is what is the best/most widely accepted way to handle a situation like this? 我的问题是,处理这种情况的最佳/最广泛接受的方法是什么?
I have tried using a try/catch statement: 我尝试使用try / catch语句:
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
http://jsfiddle.net/fmpeyton/7w60cesp/ http://jsfiddle.net/fmpeyton/7w60cesp/
This works perfectly fine, but feels dirty. 这样可以很好地工作,但是感觉很脏。 Maybe because I usually do not handle JS fatal errors.
也许是因为我通常不处理JS致命错误。 Is it very common to handle fatal errors more gracefully in a scenario like this?
在这种情况下更优雅地处理致命错误是否很常见?
Doing a try catch makes sense but if JSON.parse
throws an error because of something else than your output
variable could end up containing something that you did not intend. 进行try catch是有道理的,但是如果
JSON.parse
由于除output
变量之外的其他原因而引发错误,则最终可能包含您不想要的内容。
That's an interesting problem though. 不过,这是一个有趣的问题。 I would do something like this - basically checking for the presence of
{
and }
in the string: 我会做这样的事情-基本上检查字符串中
{
和}
是否存在:
function parseCookieString(str){
var output;
if (!!str.match(/^{.+}$/)) {
output = JSON.parse(str);
} else {
output = str;
}
console.log(output);
}
parseCookieString(cookie1); // outputs object
parseCookieString(cookie2); // outputs string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.