From 8dafcd2c96a63ed11ab833b43a980ead23eb08e9 Mon Sep 17 00:00:00 2001 From: Philipp Date: Thu, 6 Nov 2014 17:19:34 +0100 Subject: [PATCH] Throw exception if postParams parsing fails --- lib/middleware/params.js | 20 +++++++++++++++----- test/middleware/params_test.js | 8 ++++++-- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/middleware/params.js b/lib/middleware/params.js index 5e7fe7b..f68753b 100644 --- a/lib/middleware/params.js +++ b/lib/middleware/params.js @@ -9,6 +9,7 @@ var {isFileUpload, isUrlEncoded, parseFileUpload, parseParameters, mergeParameter, BufferFactory} = require("ringo/utils/http"); var objects = require("ringo/utils/objects"); var strings = require("ringo/utils/strings"); +var response = require("ringo/jsgi/response"); /** * Middleware for parsing HTTP parameters. @@ -21,6 +22,13 @@ var strings = require("ringo/utils/strings"); */ exports.middleware = function params(next, app) { + // Custom Error + function ParamsParseException (message) { + this.name = 'ParamsParseException'; + this.message = message; + this.stack = (new Error()).stack; + }; + return function(req) { var params, queryParams, postParams; @@ -90,10 +98,8 @@ exports.middleware = function params(next, app) { input = req.input.read(); try { postParams = JSON.parse(input.decodeToString(encoding)); - } catch (e if e instanceof SyntaxError) { - // developers can react on empty post parameters - // instead of throwing a hard syntax error - postParams = {}; + } catch (e) { + throw new ParamsParseException(); } } } @@ -107,7 +113,11 @@ exports.middleware = function params(next, app) { }, configurable: true, enumerable: true }); - return next(req); + try { + return next(req); + } catch (e if e instanceof ParamsParseException) { + return response.bad(); + } }; }; \ No newline at end of file diff --git a/test/middleware/params_test.js b/test/middleware/params_test.js index b340265..8d76fc0 100644 --- a/test/middleware/params_test.js +++ b/test/middleware/params_test.js @@ -33,7 +33,8 @@ exports.testJSONParsing = function() { }); app.post("/bad", function (req) { - assert.deepEqual(req.postParams, {}); + // Try to access post params + req.postParams; }); app(mockRequest("POST", "/good", { @@ -43,12 +44,15 @@ exports.testJSONParsing = function() { input: new io.MemoryStream(new binary.ByteString("{\"foo\": \"bar\"}", "UTF-8")) })); - app(mockRequest("POST", "/bad", { + var response = app(mockRequest("POST", "/bad", { headers: { "content-type": "application/json" }, input: new io.MemoryStream(new binary.ByteString("{foo: \"bar\"}", "UTF-8")) })); + + // Check for Bad Request + assert.strictEqual(response.status, 400); }; exports.testPostParamsParsing = function() {