@vtex/api
Version:
VTEX I/O API client
86 lines (85 loc) • 3.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.error = void 0;
const constants_1 = require("../../../../../constants");
const RequestCancelledError_1 = require("../../../../../errors/RequestCancelledError");
const TooManyRequestsError_1 = require("../../../../../errors/TooManyRequestsError");
const error_1 = require("../../../../../utils/error");
const logger_1 = require("../../../../logger");
const CACHE_CONTROL_HEADER = 'cache-control';
const META_HEADER = 'x-vtex-meta';
const ETAG_HEADER = 'etag';
const TWO_SECONDS_S = 2;
const production = process.env.VTEX_PRODUCTION === 'true';
// todo: unify GraphQL and REST exception treatment
const logAndRemoveSensitiveData = (ctx, err) => {
const { method, status, query, vtex: { operationId, requestId, route: { id, params, }, serverTiming, }, headers: { 'x-forwarded-path': forwardedPath, 'x-forwarded-host': forwardedHost, 'x-forwarded-proto': forwardedProto, 'x-vtex-caller': caller, 'x-vtex-platform': platform, 'x-vtex-product': product, 'x-vtex-locale': locale, }, } = ctx;
// Grab level from originalError, default to "error" level.
let level = err && err.level;
if (!level || !(level === logger_1.LogLevel.Error || level === logger_1.LogLevel.Warn)) {
level = logger_1.LogLevel.Error;
}
const log = {
...err,
caller,
forwardedHost,
forwardedPath,
forwardedProto,
locale,
method,
operationId,
params,
platform,
product,
query,
requestId,
routeId: id,
serverTiming,
status,
};
// Use sendLog directly to avoid cleaning error twice.
ctx.vtex.logger.log(log, level);
if (!constants_1.LINKED) {
error_1.SENSITIVE_EXCEPTION_FIELDS.forEach(field => {
delete err[field];
});
}
};
async function error(ctx, next) {
var _a;
try {
await next();
}
catch (e) {
if (e instanceof RequestCancelledError_1.RequestCancelledError) {
ctx.status = RequestCancelledError_1.cancelledRequestStatus;
return;
}
if (e instanceof TooManyRequestsError_1.TooManyRequestsError) {
ctx.status = TooManyRequestsError_1.tooManyRequestsStatus;
return;
}
console.error('[node-vtex-api error]', e);
const err = (0, error_1.cleanError)(e);
// Add response
ctx.status = (e === null || e === void 0 ? void 0 : e.status) && e.status >= 400 && e.status <= 599
? e.status
: ctx.status >= 500 && ctx.status <= 599
? ctx.status
: 500;
// Do not generate etag for errors
ctx.remove(META_HEADER);
ctx.remove(ETAG_HEADER);
(_a = ctx.vtex.recorder) === null || _a === void 0 ? void 0 : _a.clear();
// In production errors, add two second cache
if (production) {
ctx.set(CACHE_CONTROL_HEADER, `public, max-age=${TWO_SECONDS_S}`);
}
else {
ctx.set(CACHE_CONTROL_HEADER, `no-cache, no-store`);
}
logAndRemoveSensitiveData(ctx, err);
ctx.body = ctx.body || err;
}
}
exports.error = error;