Skip to content

Commit

Permalink
fix: return proper API-style response if exception caught by error ha…
Browse files Browse the repository at this point in the history
…ndler on v3 routes [breaking]
  • Loading branch information
julianlam committed Jul 9, 2021
1 parent ae14016 commit a54a3ee
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
14 changes: 9 additions & 5 deletions src/controllers/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)) {
Expand Down

0 comments on commit a54a3ee

Please sign in to comment.