@fairmint/canton-node-sdk
Version:
Canton Node SDK
72 lines • 3.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketErrorUtils = void 0;
const zod_1 = require("zod");
const errors_1 = require("../errors");
/** Utility functions for consistent WebSocket error handling */
class WebSocketErrorUtils {
/**
* Safely parses a message using multiple schemas, throwing descriptive errors if all fail
*
* @param msg - The message to parse
* @param schemas - Array of schemas to try in order
* @param operationName - Name of the operation for error context
* @returns The parsed message
* @throws CantonError if all schemas fail to parse
*/
static parseWithFallback(msg, schemas, operationName) {
const errors = [];
for (const { schema, name } of schemas) {
try {
return schema.parse(msg);
}
catch (error) {
if (error instanceof zod_1.z.ZodError) {
errors.push(`${name}: ${error.issues.map((e) => e.message).join(', ')}`);
}
else {
errors.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
throw new errors_1.CantonError(`Failed to parse ${operationName} message with any expected schema. Errors: ${errors.join('; ')}`, 'VALIDATION_ERROR', { originalMessage: msg, attemptedSchemas: schemas.map((s) => s.name) });
}
/**
* Parses a union schema and returns the result without type assertion
*
* @param msg - The message to parse
* @param unionSchema - The Zod union schema
* @param operationName - Name of the operation for error context
* @returns The parsed message with proper typing
* @throws CantonError if parsing fails
*/
static parseUnion(msg, unionSchema, operationName) {
try {
return unionSchema.parse(msg);
}
catch (error) {
if (error instanceof zod_1.z.ZodError) {
throw new errors_1.CantonError(`Failed to parse ${operationName} message: ${error.issues.map((e) => e.message).join(', ')}`, 'VALIDATION_ERROR', { originalMessage: msg, validationErrors: error.issues });
}
throw new errors_1.CantonError(`Failed to parse ${operationName} message: ${error instanceof Error ? error.message : String(error)}`, 'VALIDATION_ERROR', { originalMessage: msg });
}
}
/**
* Creates a safe JSON parser that throws descriptive errors
*
* @param data - Raw data to parse
* @param context - Context for error messages
* @returns Parsed JSON object
* @throws CantonError if JSON parsing fails
*/
static safeJsonParse(data, context) {
try {
return JSON.parse(data);
}
catch (error) {
throw new errors_1.CantonError(`Failed to parse JSON in ${context}: ${error instanceof Error ? error.message : String(error)}`, 'VALIDATION_ERROR', { rawData: data, context });
}
}
}
exports.WebSocketErrorUtils = WebSocketErrorUtils;
//# sourceMappingURL=WebSocketErrorUtils.js.map