Skip to content

Commit

Permalink
refactor: better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
zeyu2001 committed Jul 15, 2024
1 parent 0243b06 commit 539f7c1
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 9 deletions.
3 changes: 2 additions & 1 deletion packages/validators/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
},
"dependencies": {
"vitest": "^2.0.2",
"zod": "^3.23.8"
"zod": "^3.23.8",
"zod-validation-error": "^3.3.0"
},
"devDependencies": {
"@types/node": "^18",
Expand Down
14 changes: 7 additions & 7 deletions packages/validators/src/url/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ZodError } from 'zod'
import { fromError } from 'zod-validation-error'

import { OptionsError, UrlValidationError } from '@/url/errors'
import { defaultOptions, Options, optionsSchema } from '@/url/options'
Expand All @@ -8,13 +9,12 @@ export class UrlValidator {
private schema

constructor(options: Options = defaultOptions) {
let validatedOptions: Options
try {
validatedOptions = optionsSchema.parse({ ...defaultOptions, ...options })
} catch (error) {
throw new OptionsError(`Invalid options: ${(error as Error).message}`)
const result = optionsSchema.safeParse({ ...defaultOptions, ...options })
if (result.success) {
this.schema = createUrlSchema(result.data)
return
}
this.schema = createUrlSchema(validatedOptions)
throw new OptionsError(fromError(result.error))
}

parse(url: string): URL {
Expand All @@ -23,7 +23,7 @@ export class UrlValidator {
return result.data
}
if (result.error instanceof ZodError) {
throw new UrlValidationError(JSON.stringify(result.error.format()))
throw new UrlValidationError(fromError(result.error))
} else {
throw result.error
}
Expand Down
12 changes: 11 additions & 1 deletion packages/validators/src/url/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ export type Whitelist = z.infer<typeof whitelistSchema>
export const optionsSchema = z.object({
baseUrl: z
.string()
.transform((value) => new URL(value))
.transform((value, ctx) => {
try {
return new URL(value)
} catch (error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: (error as Error).message,
})
return z.NEVER
}
})
.refine(
(value) => value.protocol === 'http:' || value.protocol === 'https:',
)
Expand Down
13 changes: 13 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 539f7c1

Please sign in to comment.