From 9d63564719f703fd6ba6ed9fbe0886fe00f049bb Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Sun, 14 Jun 2020 21:48:50 +0200 Subject: [PATCH] Promote ValidationBag error handling to Application wide level --- src/Application.ts | 9 ++++++++- src/Controller.ts | 13 ++----------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/Application.ts b/src/Application.ts index 1b723aa..4b9a1c7 100644 --- a/src/Application.ts +++ b/src/Application.ts @@ -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 {lib} from "nunjucks"; import Logger from "./Logger"; @@ -9,6 +9,7 @@ import MysqlConnectionManager from "./db/MysqlConnectionManager"; import Migration from "./db/Migration"; import {Type} from "./Utils"; import LogRequestsComponent from "./components/LogRequestsComponent"; +import {ValidationBag} from "./db/Validator"; import TemplateError = lib.TemplateError; export default abstract class Application { @@ -69,6 +70,12 @@ export default abstract class Application { 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 httpError: HttpError; diff --git a/src/Controller.ts b/src/Controller.ts index e5b587e..605abd5 100644 --- a/src/Controller.ts +++ b/src/Controller.ts @@ -98,24 +98,15 @@ export default abstract class Controller { private wrap(handler: RequestHandler): RequestHandler { return (req, res, next) => { - function handleErr(e: any) { - if (e instanceof ValidationBag) { - req.flash('validation', e.getMessages()); - res.redirectBack(); - } else { - next(e); - } - } - try { const promise = handler.call(this, req, res, next); if (promise instanceof Promise) { promise.catch(e => { - handleErr(e); + next(e); }); } } catch (e) { - handleErr(e); + next(e); } }; }