Skip to content

Commit 972d410

Browse files
KalleVachrinza
authored andcommitted
fix(html): avoid rendering [Object object] for undefined values
Signed-off-by: KalleV <[email protected]>
1 parent 71f84a5 commit 972d410

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

lib/send-html.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ const compiledTemplates = {
1616

1717
module.exports = sendHtml;
1818

19+
const STANDARD_PROPS = ['name', 'statusCode', 'message', 'stack'];
20+
1921
/**
2022
* Sends HTML response to the client.
2123
*
@@ -24,7 +26,16 @@ module.exports = sendHtml;
2426
* @param {Object} options - The options object.
2527
*/
2628
function sendHtml(res, data, options) {
27-
const toRender = {options, data};
29+
// Filter out properties with undefined / null values and keep standard properties
30+
const filteredData = Object.keys(data).reduce((obj, key) => {
31+
if (data[key] || STANDARD_PROPS.includes(key)) {
32+
obj[key] = data[key];
33+
}
34+
return obj;
35+
}, {});
36+
37+
const toRender = {options, data: filteredData};
38+
2839
// TODO: ability to call non-default template functions from options
2940
const body = compiledTemplates.default(toRender);
3041
sendResponse(res, body);
@@ -50,8 +61,7 @@ handlebars.registerHelper('partial', partial);
5061
* @returns {string} - The result of the Handlebars template.
5162
*/
5263
function standardProps(prop, options) {
53-
const standardProps = ['name', 'statusCode', 'message', 'stack'];
54-
if (standardProps.indexOf(prop) === -1) {
64+
if (STANDARD_PROPS.indexOf(prop) === -1) {
5565
return options.fn(this);
5666
}
5767
return options.inverse(this);

test/handler.test.mjs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,6 +683,27 @@ describe('strong-error-handler', function() {
683683
});
684684
});
685685

686+
it('hides undefined properties from the HTML response', function(done) {
687+
const error = new ErrorWithProps({
688+
message: 'A test error message',
689+
details: undefined,
690+
code: undefined,
691+
});
692+
error.statusCode = 400;
693+
givenErrorHandlerForError(error);
694+
requestHTML()
695+
.end(function(err, res) {
696+
expect(res.statusCode).to.eql(400);
697+
698+
const body = res.error.text;
699+
700+
expect(body).to.match(/400(.*?)A test error message/);
701+
expect(body).not.to.match(/details/);
702+
expect(body).not.to.match(/code/);
703+
done();
704+
});
705+
});
706+
686707
function requestHTML(url) {
687708
return request.get(url || '/')
688709
.set('Accept', 'text/html')

0 commit comments

Comments
 (0)