feat: enhance error handling in /payer route with detailed context and add ABN format validation

This commit is contained in:
Astrian Zheng 2025-01-12 08:02:37 +11:00
parent ed85337715
commit 3446954648
Signed by: Astrian
SSH Key Fingerprint: SHA256:rVnhx3DAKjujCwWE13aDl7uV6+9U1MvydLkNRXJrBiA
2 changed files with 25 additions and 7 deletions

View File

@ -19,7 +19,9 @@ app.use(async (ctx, next) => {
} catch (e) {
if (e instanceof HttpError) {
ctx.status = e.status
ctx.body = JSON.stringify({ error: e.message })
let errorBody: { error: string, context?: string[] } = { error: e.message }
if (e.context) errorBody['context'] = e.context
ctx.body = JSON.stringify(errorBody)
} else {
console.log(e)
ctx.status = 500
@ -28,6 +30,7 @@ app.use(async (ctx, next) => {
}
})
// 具体路由
app.use(route.get('/', (ctx) => {
ctx.body = 'Hello World'
}))
@ -37,21 +40,29 @@ app.use(route.post('/payer', async (ctx) => {
// 验证必填字段
// 字段缺失时
if (!ctx.request.body) throw new HttpError(ErrorDescEnum.required_fields_missing, 400)
if (!ctx.request.body) throw new HttpError(ErrorDescEnum.required_fields_missing, 400, ['name', 'address', 'email'])
// 有字段,但为空时
const { name, address, email, abn } = ctx.request.body
if (!name || !address || !email) throw new HttpError(ErrorDescEnum.required_fields_missing, 400)
let emptyFields = []
if (!name) emptyFields.push('name')
if (!address) emptyFields.push('address')
if (!email) emptyFields.push('email')
if (emptyFields.length > 0) throw new HttpError(ErrorDescEnum.required_fields_missing, 400, emptyFields)
// 验证地址格式,格式应为 string[],最多两行
if (!Array.isArray(address) || address.length > 2 || address.length <= 0) throw new HttpError(ErrorDescEnum.invalid_field_format, 400)
if (!Array.isArray(address) || address.length > 2 || address.length <= 0) throw new HttpError(ErrorDescEnum.invalid_field_format, 400, ['address'])
// 名字应为字符串
if (typeof name !== 'string') throw new HttpError(ErrorDescEnum.invalid_field_format, 400)
if (typeof name !== 'string') throw new HttpError(ErrorDescEnum.invalid_field_format, 400, ['name'])
// 验证邮箱格式
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
if (!emailRegex.test(email)) throw new HttpError(ErrorDescEnum.invalid_field_format, 400)
if (!emailRegex.test(email)) throw new HttpError(ErrorDescEnum.invalid_field_format, 400, ['email'])
// 验证 ABN 格式
const abnRegex = /^\d{11}$/
if (abn && !abnRegex.test(abn)) throw new HttpError(ErrorDescEnum.invalid_field_format, 400, ['abn'])
// 创建新的付款人
await func.createPayer(name, address, email, abn)

View File

@ -7,16 +7,23 @@ class HttpError extends Error {
* HTTP
* @param message
* @param status
* @param context
*/
constructor(message: ErrorDescEnum, status: 400 | 401 | 403 | 404 | 500) {
constructor(message: ErrorDescEnum, status: 400 | 401 | 403 | 404 | 500, context?: string[]) {
super(message);
this.status = status;
if (context) this.context = context;
}
/**
*
*/
status: 400 | 401 | 403 | 404 | 500;
/**
*
*/
context?: string[];
}
/**