introduced new exception classes for structured error reporting

This commit is contained in:
zadam
2022-12-09 16:04:13 +01:00
parent eaf195e0c8
commit 342ae6e5e2
27 changed files with 123 additions and 64 deletions

View File

@@ -5,6 +5,7 @@ const loginRoute = require('./login');
const indexRoute = require('./index');
const utils = require('../services/utils');
const multer = require('multer');
const ValidationError = require("../errors/validation_error.js");
// API routes
const treeApiRoute = require('./api/tree');
@@ -61,6 +62,7 @@ const csurf = require('csurf');
const {createPartialContentHandler} = require("express-partial-content");
const rateLimit = require("express-rate-limit");
const AbstractEntity = require("../becca/entities/abstract_entity");
const NotFoundError = require("../errors/not_found_error.js");
const csrfMiddleware = csurf({
cookie: true,
@@ -169,13 +171,7 @@ function route(method, path, middleware, routeHandler, resultHandler, transactio
log.request(req, res, Date.now() - start, responseLength);
})
.catch(e => {
log.error(`${method} ${path} threw exception: ` + e.stack);
res.setHeader("Content-Type", "text/plain")
.status(500)
.send(e.message);
});
.catch(e => handleException(method, path, e, res));
}
else {
const responseLength = resultHandler(req, res, result);
@@ -185,15 +181,33 @@ function route(method, path, middleware, routeHandler, resultHandler, transactio
}
}
catch (e) {
log.error(`${method} ${path} threw exception: ` + e.stack);
res.setHeader("Content-Type", "text/plain")
.status(500)
.send(e.message);
handleException(method, path, e, res);
}
});
}
function handleException(method, path, e, res) {
log.error(`${method} ${path} threw exception: ` + e.stack);
if (e instanceof ValidationError) {
res.setHeader("Content-Type", "application/json")
.status(400)
.send({
message: e.message
});
} if (e instanceof NotFoundError) {
res.setHeader("Content-Type", "application/json")
.status(404)
.send({
message: e.message
});
} else {
res.setHeader("Content-Type", "text/plain")
.status(500)
.send(e.message);
}
}
const MAX_ALLOWED_FILE_SIZE_MB = 250;
const GET = 'get', POST = 'post', PUT = 'put', PATCH = 'patch', DELETE = 'delete';