Handled unknown errors when preparing user message

- in the event we get an unknown error bubble up, we don't handle the
  templating on the error name
- `@tryghost/tpl` throws an error because we pass an undefined string:
  `Cannot read properties of undefined (reading 'replace')`
- this commit adds handling to fallback to a different user message in
  that event so we don't cause a 500 error
This commit is contained in:
Daniel Lockyer 2022-03-24 10:06:55 +00:00
parent 866c746455
commit 10e97cad23
2 changed files with 28 additions and 3 deletions

View File

@ -36,7 +36,8 @@ const messages = {
HostLimitError: 'Host Limit error, cannot {action}.',
DisabledFeatureError: 'Theme validation error, the {{{helperName}}} helper is not available. Cannot {action}.',
UpdateCollisionError: 'Saving failed! Someone else is editing this post.'
}
},
UnknownError: 'Unknown error - {name}, cannot {action}.'
};
/**
@ -161,7 +162,11 @@ const prepareUserMessage = (err, req) => {
userError.context = err.message;
}
userError.message = tpl(messages.userMessages[err.name], {action: action});
if (_.get(messages.userMessages, err.name)) {
userError.message = tpl(messages.userMessages[err.name], {action: action});
} else {
userError.message = tpl(messages.UnknownError, {action, name: err.name});
}
}
}

View File

@ -2,7 +2,7 @@
// const testUtils = require('./utils');
require('./utils');
const {InternalServerError} = require('@tryghost/errors');
const {prepareError, handleJSONResponse, handleJSONResponseV2, handleHTMLResponse, prepareStack} = require('../lib/mw-error-handler');
const {prepareError, handleJSONResponse, handleJSONResponseV2, handleHTMLResponse, prepareStack} = require('../');
describe('Prepare Error', function () {
it('Correctly prepares a normal error', function (done) {
@ -56,6 +56,26 @@ describe('Error renderers', function () {
}, () => {});
});
it('Handles unknown errors when preparing user message', function (done) {
const errorRenderer = handleJSONResponseV2({
errorHandler: () => {}
})[3];
errorRenderer(new RangeError('test!'), {
frameOptions: {
docName: 'oembed',
method: 'read'
}
}, {
json: (data) => {
data.errors.length.should.eql(1);
data.errors[0].message.should.eql('Unknown error - RangeError, cannot read oembed.');
data.errors[0].context.should.eql('test!');
done();
}
}, () => {});
});
it('Uses templates when required', function (done) {
const errorRenderer = handleJSONResponseV2({
errorHandler: () => {}