Skip to content

Node.js based forum software built for the modern web

fix: return proper API-style response if exception caught by error handler on v3 routes [breaking]

Julian Lama54a3ee1cac0
diff --git a/src/controllers/errors.js b/src/controllers/errors.js
index 92fc6ab302..1a68662d3a 100644
--- a/src/controllers/errors.js
+++ b/src/controllers/errors.js
@@ -5,7 +5,8 @@ const winston = require('winston');
const validator = require('validator');
const plugins = require('../plugins');
const middleware = require('../middleware');
-const helpers = require('../middleware/helpers');
+const middlewareHelpers = require('../middleware/helpers');
+const helpers = require('./helpers');
exports.handleURIErrors = async function handleURIErrors(err, req, res, next) {
// Handle cases where malformed URIs are passed in
@@ -53,15 +54,18 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di
return res.locals.isAPI ? res.set('X-Redirect', err.path).status(200).json(err.path) : res.redirect(nconf.get('relative_path') + err.path);
}
- winston.error(`${req.path}\n${err.stack}`);
+ const path = String(req.path || '');
- res.status(status || 500);
+ if (path.startsWith(`${nconf.get('relative_path')}/api/v3`)) {
+ return helpers.formatApiResponse(err.message.startsWith('[[') ? 400 : 500, res, err);
+ }
- const path = String(req.path || '');
+ winston.error(`${req.path}\n${err.stack}`);
+ res.status(status || 500);
const data = {
path: validator.escape(path),
error: validator.escape(String(err.message)),
- bodyClass: helpers.buildBodyClass(req, res),
+ bodyClass: middlewareHelpers.buildBodyClass(req, res),
};
if (res.locals.isAPI) {
res.json(data);
diff --git a/src/middleware/user.js b/src/middleware/user.js
index 061b791feb..f9addf483d 100644
--- a/src/middleware/user.js
+++ b/src/middleware/user.js
@@ -65,7 +65,7 @@ module.exports = function (middleware) {
return true;
}
- throw new Error('A master token was received without a corresponding `_uid` in the request body');
+ throw new Error('[[errors:api.master-token-no-uid]]');
} else {
winston.warn('[api/authenticate] Unable to find user after verifying token');
return true;
@@ -84,6 +84,7 @@ module.exports = function (middleware) {
return !res.headersSent;
}
+ // TODO: Remove in v1.18.0
middleware.authenticate = helpers.try(async (req, res, next) => {
winston.warn(`[middleware] middleware.authenticate has been deprecated, page and API routes are now automatically authenticated via setup(Page|API)Route. Use middleware.authenticateRequest (if not using route helper) and middleware.ensureLoggedIn instead. (request path: ${req.path})`);
if (!await authenticate(req, res)) {