一个 Sumor Cloud 工具。
更多文档
一个支持多语言、预定义错误码和传递数据的错误处理库。
npm i @sumor/error --save
需要Node.JS版本为16.x或更高
由于这个包是用 ES 模块编写的,
请在您的 package.json
文件中作如下更改:
{
"type": "module"
}
import defineError from '@sumor/error'
const MyError = defineError({
code: {
USER_NOT_FOUND: '用户未找到',
USER_EXISTED: '用户 {name} 已存在'
}
})
throw new MyError('USER_NOT_FOUND')
// 输出: Error: 用户未找到
throw new MyError('USER_EXISTED', { name: 'Alice' })
// 输出: Error: 用户 Alice 已存在
import defineError from '@sumor/error'
const MyError = defineError({
language: 'en', // 默认语言
code: {
USER_NOT_FOUND: 'User not found',
USER_EXISTED: 'User {name} existed'
},
i18n: {
zh: {
USER_NOT_FOUND: '用户未找到',
USER_EXISTED: '用户 {name} 已存在'
}
}
})
const error = new MyError('USER_EXISTED', { name: 'Alice' })
error.language = 'en' // 更改错误语言
console.log(error)
// 输出: Error: User Alice existed
error.language = 'zh' // 更改错误语言
console.log(error)
// 输出: Error: 用户 Alice 已存在
import defineError from '@sumor/error'
const MyError = defineError({
code: {
USER_NOT_FOUND: 'User not found',
USER_EXISTED: 'User {name} existed'
}
})
const error = new MyError('USER_EXISTED', { name: 'Alice' })
console.log(error.json())
// 输出: {"code":"USER_EXISTED","message":"User Alice existed"}
import defineError from '@sumor/error'
const MyError = defineError({
code: {
FIELD_VERIFY_FAILED: 'Field verify failed',
FIELD_CANNOT_EMPTY: 'Field {name} cannot be empty',
FIELD_TOO_LONG: 'Field {name} is too long'
},
i18n: {
zh: {
FIELD_VERIFY_FAILED: '字段验证失败',
FIELD_CANNOT_EMPTY: '字段 {name} 不能为空',
FIELD_TOO_LONG: '字段 {name} 过长'
}
}
})
const error = new MyError('FIELD_VERIFY_FAILED', {}, [
new MyError('FIELD_CANNOT_EMPTY', { name: 'username' }),
new MyError('FIELD_TOO_LONG', { name: 'password' })
])
console.log(error.json())
/*
输出:
{
"code":"FIELD_VERIFY_FAILED",
"message":"字段验证失败",
"errors":[
{
"code":"FIELD_CANNOT_EMPTY",
"message":"字段 username 不能为空"
},{
"code":"FIELD_TOO_LONG",
"message":"字段 password 过长"
}
]
}
*/
error.language = 'zh'
console.log(error.json())
/*
输出:
{
"code":"FIELD_VERIFY_FAILED",
"message":"字段验证失败",
"errors":[
{
"code":"FIELD_CANNOT_EMPTY",
"message":"字段 username 不能为空"
},{
"code":"FIELD_TOO_LONG",
"message":"字段 password 过长"
}
]
}
*/
import defineError from '@sumor/error'
const MyError = defineError({
code: {
FIELD_VERIFY_FAILED: 'Field verify failed',
FIELD_CANNOT_EMPTY: 'Field {name} cannot be empty',
FIELD_TOO_LONG: 'Field {name} is too long'
}
})
const error = new MyError('FIELD_VERIFY_FAILED', {}, [
new MyError('FIELD_CANNOT_EMPTY', { name: 'username' }),
new MyError('FIELD_TOO_LONG', { name: 'password' }),
new Error('Unknown Error')
])
console.log(error.json())
/*
输出:
{
"code":"FIELD_VERIFY_FAILED",
"message":"Field verify failed",
"errors":[
{
"code":"FIELD_CANNOT_EMPTY",
"message":"Field username 不能为空"
},{
"code":"FIELD_TOO_LONG",
"message":"Field password 过长"
},{
"code":"UNKNOWN_ERROR",
"message":"Unknown Error"
}
]
}
*/