Skip to content

Commit 2d522c4

Browse files
committed
feat: added support for passport-local-mongoose error message translation
1 parent e422299 commit 2d522c4

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

src/index.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,18 @@ const _500 = fs.readFileSync(path.join(__dirname, '..', '500.html'), opts);
1717

1818
const debug = new Debug('koa-better-error-handler');
1919

20+
const passportLocalMongooseErrorNames = [
21+
'AuthenticationError',
22+
'MissingPasswordError',
23+
'AttemptTooSoonError',
24+
'TooManyAttemptsError',
25+
'NoSaltValueStoredError',
26+
'IncorrectPasswordError',
27+
'IncorrectUsernameError',
28+
'MissingUsernameError',
29+
'UserExistsError'
30+
];
31+
2032
// initialize try/catch error handling right away
2133
// adapted from: https://github.com/koajs/onerror/blob/master/index.js
2234
// https://github.com/koajs/examples/issues/20#issuecomment-31568401
@@ -202,6 +214,21 @@ async function errorHandler(err) {
202214
}
203215

204216
function parseValidationError(ctx, err) {
217+
// translate messages
218+
const translate = message =>
219+
_.isFunction(ctx.request.t) ? ctx.request.t(message) : message;
220+
221+
// passport-local-mongoose support
222+
if (passportLocalMongooseErrorNames.includes(err.name)) {
223+
err.message = translate(err.message);
224+
// this ensures the error shows up client-side
225+
err.status = 400;
226+
// 429 = too many requests
227+
if (['AttemptTooSoonError', 'TooManyAttemptsError'].includes(err.name))
228+
err.status = 429;
229+
return err;
230+
}
231+
205232
// inspired by https://github.com/syntagma/mongoose-error-helper
206233
if (err.name !== 'ValidationError') return err;
207234

@@ -221,10 +248,6 @@ function parseValidationError(ctx, err) {
221248
return error;
222249
});
223250

224-
// translate messages
225-
const translate = message =>
226-
_.isFunction(ctx.request.t) ? ctx.request.t(message) : message;
227-
228251
// loop over the errors object of the Validation Error
229252
// with support for HTML error lists
230253
if (_.values(err.errors).length === 1) {
@@ -238,7 +261,6 @@ function parseValidationError(ctx, err) {
238261

239262
// this ensures the error shows up client-side
240263
err.status = 400;
241-
err.statusCode = 400;
242264

243265
return err;
244266
}

0 commit comments

Comments
 (0)