Promote ValidationBag error handling to Application wide level

This commit is contained in:
Alice Gaudon 2020-06-14 21:48:50 +02:00
parent fa3e5bdb19
commit 9d63564719
2 changed files with 10 additions and 12 deletions

View File

@ -1,4 +1,4 @@
import express, {NextFunction, Request, RequestHandler, Response, Router} from 'express'; import express, {NextFunction, Request, Response, Router} from 'express';
import {BadRequestError, HttpError, NotFoundHttpError, ServerError, ServiceUnavailableHttpError} from "./HttpError"; import {BadRequestError, HttpError, NotFoundHttpError, ServerError, ServiceUnavailableHttpError} from "./HttpError";
import {lib} from "nunjucks"; import {lib} from "nunjucks";
import Logger from "./Logger"; import Logger from "./Logger";
@ -9,6 +9,7 @@ import MysqlConnectionManager from "./db/MysqlConnectionManager";
import Migration from "./db/Migration"; import Migration from "./db/Migration";
import {Type} from "./Utils"; import {Type} from "./Utils";
import LogRequestsComponent from "./components/LogRequestsComponent"; import LogRequestsComponent from "./components/LogRequestsComponent";
import {ValidationBag} from "./db/Validator";
import TemplateError = lib.TemplateError; import TemplateError = lib.TemplateError;
export default abstract class Application { export default abstract class Application {
@ -69,6 +70,12 @@ export default abstract class Application {
return next(err); return next(err);
} }
if (err instanceof ValidationBag) {
req.flash('validation', err.getMessages());
res.redirectBack();
return;
}
let errorID: string = LogRequestsComponent.logRequest(req, res, err, '500 Internal Error', err instanceof BadRequestError || err instanceof ServiceUnavailableHttpError); let errorID: string = LogRequestsComponent.logRequest(req, res, err, '500 Internal Error', err instanceof BadRequestError || err instanceof ServiceUnavailableHttpError);
let httpError: HttpError; let httpError: HttpError;

View File

@ -98,24 +98,15 @@ export default abstract class Controller {
private wrap(handler: RequestHandler): RequestHandler { private wrap(handler: RequestHandler): RequestHandler {
return (req, res, next) => { return (req, res, next) => {
function handleErr(e: any) {
if (e instanceof ValidationBag) {
req.flash('validation', e.getMessages());
res.redirectBack();
} else {
next(e);
}
}
try { try {
const promise = handler.call(this, req, res, next); const promise = handler.call(this, req, res, next);
if (promise instanceof Promise) { if (promise instanceof Promise) {
promise.catch(e => { promise.catch(e => {
handleErr(e); next(e);
}); });
} }
} catch (e) { } catch (e) {
handleErr(e); next(e);
} }
}; };
} }