Created
February 13, 2013 04:18
-
-
Save jrgm/4942228 to your computer and use it in GitHub Desktop.
Use app.error to return JSON.parse snafus as '400 Bad Request'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/bin/verifier b/bin/verifier | |
index 1c108fd..d04c6d2 100755 | |
--- a/bin/verifier | |
+++ b/bin/verifier | |
@@ -61,6 +61,24 @@ if (statsd_config && statsd_config.enabled) { | |
app.use(express.bodyParser()); | |
+app.error(function(err, req, resp, next) { | |
+ if (!err) return next(); | |
+ | |
+ // Handle JSON.parse errors from connect.bodyParser as '400 Bad Request'. This | |
+ // can happen when the Content-Type header is 'application/json' and the body | |
+ // is some other format. Or, of course if the JSON is just flat out malformed. | |
+ | |
+ var ct = (req && req.headers && req.headers['content-type']); | |
+ if (ct === 'application/json' && err instanceof SyntaxError) { | |
+ var reason = "SyntaxError with 'Content-Type: application/json': " + err.toString(); | |
+ logger.error(reason); | |
+ return resp.json({ status: "SyntaxError", reason: reason}, 400); | |
+ } | |
+ | |
+ // We can't handle this error. Next! | |
+ next(); | |
+}); | |
+ | |
try { | |
// explicitly relay VAR_PATH to children | |
process.env['VAR_PATH'] = config.get('var_path'); |
Could probably be a statsd output, so we have a little granularity on 400 reasons.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs a bunch of tests, of course. But existing tests pass locally.