javascript - Handling bad JSON.parse() in node safely -


using node/express - want json out of request headers, want safely.
if reason it's not valid json, it's fine, can return false or whatever , reject request , keep going. problem throws syntax error if it's not valid json. want syntax error blow up, not in case.

var boom = json.parse(req.headers.myheader);

do scrape stack , check bad parse call particular module, , if it's case, ignores it? seems bit crazy. surely there's better way.

edit: aware try/catch blocks a way of handling error, best way in node app? way block node?

the best way catch invalid json parsing errors put calls json.parse() try/catch block.

you not have other option - built-in implementation throws exception on invalid json data , way prevent exception halting application catch it. using 3rd party library not avoid - must try/catch on json.parse() call somewhere.

the alternative implement own json parsing algorithm more forgiving on invalid data structures, feels digging 1 cubic metre hole small nuke.

note performance

the v8 javascript engine used node.js cannot optimise functions contain try/catch block.

update: v8 4.5 , above can optimise try/catch. older releases, see below.

a simple workaround put safe-parsing logic separate function main function can still optimised:

function safelyparsejson (json) {   // function cannot optimised, it's best   // keep small!   var parsed    try {     parsed = json.parse(json)   } catch (e) {     // oh well, whatever...   }    return parsed // undefined! }  function doalotofstuff () {   // ... stuff stuff stuff   var json = safelyparsejson(data)   // tadaa, got rid of optimisation killer! } 

if json parsing done sporadically, might not have noticeable effect on performance, if used improperly in usage-heavy function lead dramatic increase in response times.

note try/catch being blocking

it should noted every.single.statement of javascript code in node.js executed one-at-a-time, no matter if it's called main function or callback or different module or whatever. such, every single statement will block process. not bad thing - designed application spend of time waiting external resource (database response, http communication, filesystem operations etc.). therefore of great importance executed javascript code can optimised v8 engine takes little time possible in blocked state - see note performance.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -