Skip to content

Commit

Permalink
Throw exception if postParams parsing fails
Browse files Browse the repository at this point in the history
  • Loading branch information
botic committed Nov 6, 2014
1 parent 3781053 commit 8dafcd2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
20 changes: 15 additions & 5 deletions lib/middleware/params.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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();
}
}
}
Expand All @@ -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();
}
};

};
8 changes: 6 additions & 2 deletions test/middleware/params_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Expand All @@ -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() {
Expand Down

0 comments on commit 8dafcd2

Please sign in to comment.