Error handling: transform single validation errors into a validation bag

This commit is contained in:
Alice Gaudon 2020-11-14 16:24:00 +01:00
parent 3d819f03c7
commit acc5233185
2 changed files with 13 additions and 5 deletions

View File

@ -8,7 +8,7 @@ import MysqlConnectionManager from "./db/MysqlConnectionManager";
import Migration, {MigrationType} from "./db/Migration";
import {Type} from "./Utils";
import LogRequestsComponent from "./components/LogRequestsComponent";
import {ValidationBag} from "./db/Validator";
import {ValidationBag, ValidationError} from "./db/Validator";
import config from "config";
import * as fs from "fs";
import SecurityError from "./SecurityError";
@ -91,7 +91,15 @@ export default abstract class Application implements Extendable<ApplicationCompo
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
if (res.headersSent) return next(err);
// Transform single validation errors into a validation bag for convenience
if (err instanceof ValidationError) {
const bag = new ValidationBag();
bag.addMessage(err);
err = bag;
}
if (err instanceof ValidationBag) {
const bag = err;
res.format({
json: () => {
res.status(401);
@ -99,15 +107,15 @@ export default abstract class Application implements Extendable<ApplicationCompo
status: 'error',
code: 401,
message: 'Invalid form data',
messages: err.getMessages(),
messages: bag.getMessages(),
});
},
text: () => {
res.status(401);
res.send('Error: ' + err.getMessages());
res.send('Error: ' + bag.getMessages());
},
html: () => {
req.flash('validation', err.getMessages());
req.flash('validation', bag.getMessages());
res.redirectBack();
},
});

View File

@ -313,7 +313,7 @@ export class ValidationBag<V> extends Error {
}
}
export abstract class ValidationError<V> extends Error {
export class ValidationError<V> extends Error {
public rawValueToHuman?: (val: V) => string;
public thingName?: string;
public value?: V;