处理节点安全的JSON.parse() [英] Handling bad JSON.parse() in node safely

查看:123
本文介绍了处理节点安全的JSON.parse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用node / express -
我想从请求头中获取一些JSON,但是我想要安全地执行。

如果由于某种原因,它不是有效的JSON,没关系,它可以返回false或者任何东西,它只会拒绝请求并继续进行。问题是如果JSON无效,会引发语法错误。通常我想要一个语法错误,但在这种情况下不会。



var boom = JSON.parse(req.headers.myHeader) ;



我是否抓取堆栈并检查该特定模块的错误解析调用,如果是这样,它会忽略它?这似乎有点疯狂。确实有一个更好的方法。



编辑:
我知道try / catch块是 A 处理此错误的方式,但它是节点应用程序中的最佳方式吗?

解决方案

标准的try / catch是处理节点中JSON.parse错误的正确方法。 js,如节点错误处理的生产实践中提到的,来自欢乐网站的文档,它说:


...你使用try / catch的唯一常用的例子是JSON.parse
和其他用户输入验证函数。


哪些也与Aleksandr在其评论中提供的nodejitsu的链接一致。 / p>

Using node/express - I want to get some JSON out of request headers, but I want to do it safely.
If for some reason it's not valid JSON, it's fine, it can just return false or whatever and it will just reject the request and keep going. The problem is it throws a syntax error if it's not valid JSON. Normally I want a syntax error to blow up, but not in this case.

var boom = JSON.parse(req.headers.myHeader);

Do I scrape the stack and check for a bad parse call from that particular module, and if it's the case, it ignores it? That seems a bit crazy. Surely there's a better way.

EDIT: I am aware that try/catch blocks are A way of handling this error, but is it the best way in a node app? Will this way block node?

解决方案

The standard try/catch is the correct way to handle a JSON.parse error in node.js, as mentioned in the node production practices for error handling docs from the joyent website, which says:

...the only commonly-used case where you'd use try/catch is JSON.parse and other user-input validation functions.

Which is also in agreement with the link to nodejitsu which Aleksandr supplied in his comment.

这篇关于处理节点安全的JSON.parse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆