Skip to content

Instantly share code, notes, and snippets.

@jrgm
Created February 13, 2013 04:18
Show Gist options
  • Save jrgm/4942228 to your computer and use it in GitHub Desktop.
Save jrgm/4942228 to your computer and use it in GitHub Desktop.
Use app.error to return JSON.parse snafus as '400 Bad Request'
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');
@jrgm
Copy link
Author

jrgm commented Feb 13, 2013

Needs a bunch of tests, of course. But existing tests pass locally.

@jrgm
Copy link
Author

jrgm commented Feb 13, 2013

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