Error handling: transform single validation errors into a validation bag
This commit is contained in:
parent
3d819f03c7
commit
acc5233185
@ -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();
|
||||
},
|
||||
});
|
||||
|
@ -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;
|
||||
|
Loading…
Reference in New Issue
Block a user