Improve logger and responses policy

This commit is contained in:
Pierre Burgy 2017-06-23 18:50:52 +02:00
parent 969826a089
commit fd25902cbe
2 changed files with 25 additions and 21 deletions

View File

@ -25,7 +25,12 @@ module.exports = strapi => {
const start = new Date();
await next();
const ms = new Date() - start;
strapi.log.debug(ctx.method + ' ' + ctx.url + ' (' + ms + 'ms)');
// Choose logger type depending on the response status.
const logger = ctx.status < 400 ? strapi.log.debug : strapi.log.error;
// Finally, log the string.
logger(`${ctx.ip} - [${start.toISOString()}] ${ctx.method} ${ctx.status} ${ctx.url} (${ms}ms)`);
});
}

View File

@ -37,30 +37,29 @@ module.exports = async function(ctx, next) {
});
try {
// App logic.
await next();
// Set context when no route is matched.
if (_.get(ctx.request, 'route') === undefined) {
ctx.notFound();
}
if (_.get(ctx.body, 'isBoom') || _.isError(ctx.body)) {
ctx.throw();
}
} catch (error) {
// Error object could be also in the context body...
strapi.log.error(ctx.body || error);
// Wrap error into a Boom's response
const formattedError = _.get(ctx.body, 'isBoom')
? ctx.body || error.message
// Log error.
strapi.log.error(error);
// Wrap error into a Boom's response.
ctx.body = _.get(ctx.body, 'isBoom')
? ctx.body || error && error.message
: Boom.wrap(error, error.status, ctx.body || error.message);
}
ctx.status = formattedError.output.statusCode || error.status || 500;
ctx.body = formattedError.output.payload;
// Empty body is considered as `notFound` response.
if (!ctx.body) {
ctx.notFound();
}
// Call custom responses.
if (_.isFunction(_.get(strapi.config, `responses.${ctx.status}`))) {
await strapi.config.responses[ctx.status].call(this, ctx);
}
// Format `ctx.body` and `ctx.status`.
ctx.status = ctx.body.isBoom ? ctx.body.output.statusCode : ctx.status;
ctx.body = ctx.body.isBoom ? ctx.body.output.payload : ctx.body;
// Call custom responses.
if (_.isFunction(_.get(strapi.config, `responses.${ctx.status}`))) {
await strapi.config.responses[ctx.status].call(this, ctx);
}
};