UNPKG

@chubbyts/chubbyts-api

Version:

[![CI](https://github.com/chubbyts/chubbyts-api/workflows/CI/badge.svg?branch=master)](https://github.com/chubbyts/chubbyts-api/actions?query=workflow%3ACI) [![Coverage Status](https://coveralls.io/repos/github/chubbyts/chubbyts-api/badge.svg?branch=maste

44 lines (43 loc) 1.95 kB
import { createInternalServerError, isHttpError } from '@chubbyts/chubbyts-http-error/dist/http-error'; import { createLogger } from '@chubbyts/chubbyts-log-types/dist/log'; import { throwableToError } from '@chubbyts/chubbyts-throwable-to-error/dist/throwable-to-error'; import { stringify } from 'qs'; import { stringifyResponseBody, valueToData } from '../response.js'; const eToHttpError = (e, mapToHttpError) => { if (isHttpError(e)) { return e; } try { return mapToHttpError(e); } catch (me) { const error = throwableToError(me); return createInternalServerError({ error: { name: error.name, message: error.message, stack: error.stack } }); } }; const resolvePathQueryFragment = (uri) => { const query = stringify(uri.query); return [uri.path, query ? `?${query}` : '', uri.fragment ? `#${uri.fragment}` : ''].join(''); }; export const createErrorMiddleware = (responseFactory, encoder, mapToHttpError = (e) => { throw e; }, debug = false, logger = createLogger(), loggableAttributeNames = []) => { return async (request, handler) => { try { return await handler(request); } catch (e) { const httpError = eToHttpError(e, mapToHttpError); const isClientError = httpError.status < 500; logger[isClientError ? 'info' : 'error']('Http Error', { method: request.method, pathQueryFragment: resolvePathQueryFragment(request.uri), ...Object.fromEntries(loggableAttributeNames.map((name) => [name, request.attributes[name] ?? undefined])), ...httpError, }); return stringifyResponseBody(request, responseFactory(httpError.status), encoder, valueToData(isClientError || debug ? httpError : { type: httpError.type, status: httpError.status, title: httpError.title })); } }; };