@gati-framework/runtime
Version:
Gati runtime execution engine for running handler-based applications
123 lines • 3.04 kB
JavaScript
/**
* @module runtime/gtype/errors
* @description Validation error types and formatting
*/
/**
* Create a validation error
*/
export function createValidationError(path, expected, actual, message, schema) {
return {
path,
expected,
actual,
message: message || `Expected ${expected}, got ${formatValue(actual)}`,
schema,
};
}
/**
* Format a value for error messages
*/
export function formatValue(value) {
if (value === null)
return 'null';
if (value === undefined)
return 'undefined';
if (typeof value === 'string')
return `"${value}"`;
if (typeof value === 'number')
return String(value);
if (typeof value === 'boolean')
return String(value);
if (Array.isArray(value))
return `array[${value.length}]`;
if (typeof value === 'object')
return 'object';
return String(value);
}
/**
* Format a path for error messages
*/
export function formatPath(path) {
if (path.length === 0)
return '(root)';
return path
.map((segment, index) => {
if (typeof segment === 'number') {
return `[${segment}]`;
}
return index === 0 ? segment : `.${segment}`;
})
.join('');
}
/**
* Format validation errors for display
*/
export function formatValidationErrors(errors) {
if (errors.length === 0)
return 'No validation errors';
return errors
.map((error) => {
const path = formatPath(error.path);
return ` - ${path}: ${error.message}`;
})
.join('\n');
}
/**
* Create a successful validation result
*/
export function validResult() {
return {
valid: true,
errors: [],
};
}
/**
* Create a failed validation result
*/
export function invalidResult(errors) {
return {
valid: false,
errors,
};
}
/**
* Merge multiple validation results
*/
export function mergeResults(...results) {
const allErrors = results.flatMap((r) => r.errors);
return allErrors.length === 0
? validResult()
: invalidResult(allErrors);
}
/**
* Validation exception
*/
export class ValidationException extends Error {
errors;
constructor(errors, message) {
super(message || `Validation failed with ${errors.length} error(s):\n${formatValidationErrors(errors)}`);
this.errors = errors;
this.name = 'ValidationException';
Error.captureStackTrace(this, ValidationException);
}
/**
* Get formatted error message
*/
getFormattedErrors() {
return formatValidationErrors(this.errors);
}
/**
* Get errors for a specific path
*/
getErrorsForPath(path) {
const pathStr = formatPath(path);
return this.errors.filter((e) => formatPath(e.path) === pathStr);
}
/**
* Check if a specific path has errors
*/
hasErrorsForPath(path) {
return this.getErrorsForPath(path).length > 0;
}
}
//# sourceMappingURL=errors.js.map