Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

throw custom error when zod errors #5

Merged
merged 2 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class ValidationError extends Error {
constructor(message: string) {
super(message)
this.message = `ValidationError: ${message}`
this.name = 'ValidationError'
}
}
35 changes: 24 additions & 11 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ZodError } from 'zod'

import { CACHE_DURATION_MS } from './constants'
import {
type StorageKind,
Expand All @@ -12,6 +14,7 @@ import {
} from './schema'
import { InMemoryStorage, type IStorer } from './storage'
import { SpotifyStreamer, NoopStreamer, type IStreamer, Song } from './streamers'
import { ValidationError } from './error'

// NowPlaying allows one to get the currently playing song for a streaming platform
// user.
Expand All @@ -29,19 +32,29 @@ export class NowPlaying {
provider: Providers,
args: SpotifyProviderArgs | NoopProviderArgs
) {
// use zod to guarantee we get the right variable kind in here
providerSchema.parse(provider)
this.provider = provider
try {
// use zod to guarantee we get the right variable kind in here
providerSchema.parse(provider)
this.provider = provider

this.parseArgs(args)
this.streamerArgs = args.streamerArgs
this.storageKind = args.storageKind || StorageKinds.INMEMORY
this.useCache = args.useCache || true
this.cacheDuration = args.cacheDuration || CACHE_DURATION_MS;
this.parseArgs(args)
this.streamerArgs = args.streamerArgs
this.storageKind = args.storageKind || StorageKinds.INMEMORY
this.useCache = args.useCache || true
this.cacheDuration = args.cacheDuration || CACHE_DURATION_MS;

// this is whatever storage mechanic the user selects
this.storer = this.getStorer(this.storageKind)
this.streamer = this.getStreamer()
// this is whatever storage mechanic the user selects
this.storer = this.getStorer(this.storageKind)
this.streamer = this.getStreamer()
} catch (err: unknown) {
if (err instanceof ZodError) {
// We want to display Zod errors one at a time, so we stick
// to a similar format for returning errors.
const [firstError] = err.errors
throw new ValidationError(firstError.message)
}
throw new Error((err as Error)?.message)
}
}

private parseArgs(args: unknown): void {
Expand Down