错误处理
IBest-ORM 提供了完善的错误处理系统,包含错误码、详细信息和解决建议。
错误类型
ORMError
基础错误类,所有 ORM 错误都继承自此类:
ts
import { ORMError, ErrorCode } from '@ibestservices/ibest-orm';
try {
orm.query(User).first();
} catch (e) {
if (e instanceof ORMError) {
console.log('错误码:', e.code);
console.log('错误信息:', e.message);
console.log('相关表:', e.table);
console.log('相关字段:', e.field);
console.log('建议:', e.suggestion);
// 格式化输出
console.log(e.format());
}
}ValidationError
数据验证错误:
ts
import { ValidationError } from '@ibestservices/ibest-orm';
try {
orm.insert(user);
} catch (e) {
if (e instanceof ValidationError) {
console.log('验证错误列表:');
e.errors.forEach(err => {
console.log(` 字段: ${err.field}, 原因: ${err.message}`);
});
}
}QueryError
查询执行错误:
ts
import { QueryError } from '@ibestservices/ibest-orm';
try {
orm.query(User).where({ invalid: 'condition' }).find();
} catch (e) {
if (e instanceof QueryError) {
console.log('查询错误:', e.message);
console.log('SQL:', e.sql);
}
}MigrationError
数据库迁移错误:
ts
import { MigrationError } from '@ibestservices/ibest-orm';
try {
orm.migrate(User);
} catch (e) {
if (e instanceof MigrationError) {
console.log('迁移失败:', e.message);
console.log('表:', e.table);
}
}错误码
| 错误码 | 名称 | 说明 |
|---|---|---|
| 1001 | INIT_FAILED | ORM 初始化失败 |
| 1002 | CONTEXT_NOT_FOUND | 未找到应用上下文 |
| 1003 | DATABASE_NOT_FOUND | 数据库连接未建立 |
| 2001 | TABLE_NOT_SET | 未设置数据表 |
| 2002 | INVALID_QUERY | 无效的查询条件 |
| 2003 | QUERY_FAILED | 查询执行失败 |
| 3001 | TYPE_MISMATCH | 字段类型不匹配 |
| 3002 | REQUIRED_FIELD_MISSING | 必填字段缺失 |
| 3003 | PRIMARY_KEY_MISSING | 主键值缺失 |
| 3004 | VALIDATION_FAILED | 数据验证失败 |
| 4001 | MIGRATION_FAILED | 数据库迁移失败 |
| 4002 | TABLE_NOT_EXISTS | 数据表不存在 |
| 4003 | COLUMN_NOT_EXISTS | 字段不存在 |
| 5001 | RELATION_NOT_FOUND | 关联关系未找到 |
| 5002 | FOREIGN_KEY_MISSING | 外键值缺失 |
| 5003 | CASCADE_FAILED | 级联操作失败 |
| 6001 | TRANSACTION_FAILED | 事务执行失败 |
| 6002 | ROLLBACK_FAILED | 事务回滚失败 |
| 7001 | SOFT_DELETE_NOT_CONFIGURED | 软删除未配置 |
错误信息国际化
IBest-ORM 支持中英文错误信息:
ts
import { setErrorLocale, getErrorLocale } from '@ibestservices/ibest-orm';
// 设置为英文
setErrorLocale('en');
// 设置为中文(默认)
setErrorLocale('zh');
// 获取当前语言
const locale = getErrorLocale();设置后,错误信息会以对应语言显示:
ts
// 中文模式
setErrorLocale('zh');
// 错误信息: "数据验证失败"
// 英文模式
setErrorLocale('en');
// 错误信息: "Data validation failed"最佳实践
统一错误处理
ts
import { ORMError, ValidationError, QueryError } from '@ibestservices/ibest-orm';
function handleORMError(e: Error): void {
if (e instanceof ValidationError) {
// 处理验证错误
console.error('数据验证失败:', e.errors);
} else if (e instanceof QueryError) {
// 处理查询错误
console.error('查询失败:', e.message, e.sql);
} else if (e instanceof ORMError) {
// 处理其他 ORM 错误
console.error(e.format());
} else {
// 处理未知错误
console.error('未知错误:', e);
}
}
// 使用
try {
orm.insert(user);
} catch (e) {
handleORMError(e as Error);
}事务中的错误处理
ts
try {
orm.transaction(() => {
orm.insert(user);
orm.insert(order);
});
} catch (e) {
// 事务已自动回滚
console.error('事务失败:', e);
}