@energica-city/shared-amplify-utils
Version:
Shared utilities for AWS Amplify projects
62 lines • 2.76 kB
JavaScript
import { buildWebSocketContext } from './utils';
import { setupStructuredLoggingWith, getErrorMessage } from '../utils/common';
import { logger } from '../../log';
function isOurError(error) {
return (error instanceof Error &&
Object.prototype.hasOwnProperty.call(error, '__fromErrorLibrary'));
}
function buildWebSocketLogContext(input, error, defaultContext) {
return {
...defaultContext,
...Object.fromEntries(Object.entries(error).filter(([key]) => !['name', 'message', 'stack'].includes(key))),
requestId: input.context.awsRequestId || 'unknown',
functionName: input.context.functionName,
websocket: {
connectionId: input.event.requestContext?.connectionId,
routeKey: input.event
.requestContext?.routeKey,
eventType: input.event
.requestContext?.eventType,
},
};
}
export function createWebSocketErrorHandler(config = {}) {
const { includeStackTrace = process.env.NODE_ENV === 'development', defaultContext = {}, } = config;
return async (input, next) => {
const typedInput = input;
setupStructuredLoggingWith(typedInput, (i, extra) => buildWebSocketContext(i, extra), true, defaultContext);
try {
return await next(input);
}
catch (error) {
let standardError;
if (isOurError(error)) {
standardError = error;
}
else {
logger.warn('Non-standard error thrown, wrapping with throwError', {
error,
});
const wrappedMessage = 'Non-standard error thrown to WebSocket error handler';
standardError = new Error(wrappedMessage);
standardError.originalError = error;
}
const logContext = buildWebSocketLogContext(input, standardError, defaultContext);
logger.error(getErrorMessage(standardError), {
...logContext,
...Object.fromEntries(Object.entries(standardError).filter(([key]) => !['name', 'message', 'stack'].includes(key))),
requestId: input.context.awsRequestId || 'unknown',
functionName: input.context.functionName,
websocket: {
connectionId: input.event.requestContext?.connectionId,
routeKey: input.event
.requestContext?.routeKey,
eventType: input.event.requestContext?.eventType,
},
...(includeStackTrace && { stack: standardError.stack }),
});
throw standardError;
}
};
}
//# sourceMappingURL=WebSocketErrorHandler.js.map