diff --git a/package.json b/package.json index e203e8c..5297a58 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package", "name": "@kevisual/router", - "version": "0.0.81", + "version": "0.0.82", "description": "", "type": "module", "main": "./dist/router.js", diff --git a/src/result/error.ts b/src/result/error.ts index 12d320e..975c636 100644 --- a/src/result/error.ts +++ b/src/result/error.ts @@ -1,4 +1,4 @@ -type CustomErrorOptions = { +export type CustomErrorOptions = { cause?: Error | string; code?: number; message?: string; @@ -8,7 +8,11 @@ export class CustomError extends Error { code?: number; data?: any; message: string; - constructor(code?: number | string, opts?: CustomErrorOptions) { + constructor(code?: number | string | CustomErrorOptions, opts?: CustomErrorOptions) { + if (typeof code === 'object' && code !== null) { + opts = code; + code = opts.code || 500; + } let message = opts?.message || String(code); const cause = opts?.cause; super(message, { cause }); diff --git a/src/route.ts b/src/route.ts index f24035c..b58074b 100644 --- a/src/route.ts +++ b/src/route.ts @@ -1,4 +1,4 @@ -import { CustomError } from './result/error.ts'; +import { CustomError, CustomErrorOptions } from './result/error.ts'; import { pick } from './utils/pick.ts'; import { listenProcess, MockProcess } from './utils/listen-process.ts'; import { z } from 'zod'; @@ -610,9 +610,21 @@ export class QueryRouter { importRouter(router: QueryRouter) { this.importRoutes(router.routes); } - throw(code?: number | string, message?: string, tips?: string): void; + throw(code?: number | string, message?: string): void; + throw(code?: number | string, opts?: CustomErrorOptions): void; + throw(opts?: CustomErrorOptions): void; throw(...args: any[]) { - throw new CustomError(...args); + const [args0, args1] = args; + if (args0 && typeof args0 === 'object') { + throw new CustomError(args0); + } + if (args1 && typeof args1 === 'object') { + throw new CustomError(args0, args1); + } else if (args1) { + throw new CustomError(args0, { message: args1 }); + } + // args1 不存在; + throw new CustomError(args0); } hasRoute(path: string, key: string = '') { return this.routes.find((r) => r.path === path && r.key === key);