CartoDB-SQL-API/lib/api/middlewares/error.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-10-24 21:42:33 +08:00
'use strict';
const errorHandlerFactory = require('../../services/error-handler-factory');
const { stringifyForLogs } = require('../../utils/logs');
2018-12-06 02:15:57 +08:00
const MAX_ERROR_STRING_LENGTH = 1024;
2019-12-24 01:19:08 +08:00
module.exports = function error () {
return function errorMiddleware (err, req, res, next) {
2018-03-28 19:06:39 +08:00
const errorHandler = errorHandlerFactory(err);
2019-12-24 01:19:08 +08:00
const errorResponse = errorHandler.getResponse();
if (global.settings.environment === 'development') {
errorResponse.stack = err.stack;
}
2018-03-28 16:48:08 +08:00
if (global.settings.environment !== 'test') {
// TODO: email this Exception report
2019-12-24 01:19:08 +08:00
console.error('EXCEPTION REPORT: ' + err.stack);
}
// Force inline content disposition
2019-12-24 01:19:08 +08:00
res.header('Content-Disposition', 'inline');
2018-03-28 16:48:08 +08:00
if (req && req.profiler) {
req.profiler.done('finish');
res.header('X-SQLAPI-Profiler', req.profiler.toJSONString());
}
2018-03-28 19:50:45 +08:00
setErrorHeader(errorHandler, res);
res.header('Content-Type', 'application/json; charset=utf-8');
res.status(getStatusError(errorHandler, req));
if (req.query && req.query.callback) {
res.jsonp(errorResponse);
} else {
res.json(errorResponse);
}
if (req && req.profiler) {
res.req.profiler.sendStats();
}
next();
};
};
2019-12-24 01:19:08 +08:00
function getStatusError (errorHandler, req) {
2018-03-28 19:52:45 +08:00
let statusError = errorHandler.http_status;
// JSONP has to return 200 status error
if (req && req.query && req.query.callback) {
statusError = 200;
}
return statusError;
}
2019-12-24 01:19:08 +08:00
function setErrorHeader (errorHandler, res) {
2018-03-28 19:50:45 +08:00
const errorsLog = {
context: errorHandler.context,
detail: errorHandler.detail,
hint: errorHandler.hint,
statusCode: errorHandler.http_status,
message: errorHandler.message
};
2019-02-27 17:40:49 +08:00
res.set('X-SQLAPI-Errors', stringifyForLogs(errorsLog, MAX_ERROR_STRING_LENGTH));
}