From bdceda4cb6364076055b1b8c093d25065c714260 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 22 Jun 2026 20:48:47 +0800 Subject: [PATCH] refactor(share): use custom strongly-typed error classes --- packages/api/src/public-share.ts | 84 +++++++++++-------------------- packages/api/src/share.test.ts | 5 +- packages/core/src/share/errors.ts | 31 ++++++++++++ packages/core/src/share/share.ts | 18 ++++--- 4 files changed, 75 insertions(+), 63 deletions(-) create mode 100644 packages/core/src/share/errors.ts diff --git a/packages/api/src/public-share.ts b/packages/api/src/public-share.ts index 0f648740..157e60a8 100644 --- a/packages/api/src/public-share.ts +++ b/packages/api/src/public-share.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono' +import type { Context } from 'hono' import { zValidator } from '@hono/zod-validator' import { shareService } from '@shumai/core/src/share/share' import { assetService } from '@shumai/core/src/asset/asset' @@ -11,6 +12,12 @@ import { auth } from '@shumai/core/src/auth/auth' import { prisma } from '@shumai/db' import { createCommentRequestSchema } from '@shumai/dtos' import { notificationService } from '@shumai/core/src/notification/notification' +import { + ShareLinkNotFoundError, + ShareLinkDisabledError, + ShareLinkExpiredError, + ShareLinkPasswordInvalidError, +} from '@shumai/core/src/share/errors' const app = new Hono() @@ -30,6 +37,22 @@ function toFieldInfo( } } +export function handlePublicShareError(c: Context, err: unknown) { + if (err instanceof ShareLinkPasswordInvalidError) { + return c.json({ error: 'Unauthorized' }, 401) + } + if (err instanceof ShareLinkExpiredError || err instanceof ShareLinkDisabledError) { + const msg = err instanceof Error ? err.message : String(err) + return c.json({ error: msg }, 403) + } + if (err instanceof ShareLinkNotFoundError) { + const msg = err instanceof Error ? err.message : String(err) + return c.json({ error: msg }, 404) + } + const msg = err instanceof Error ? err.message : String(err) + return c.json({ error: msg }, 500) +} + const sharedChildrenRequestSchema = paginationParamsSchema.extend({ assetType: z.string().optional(), }) @@ -54,21 +77,7 @@ const route = app defaultSortOrder: shareLink.defaultSortOrder, }) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - if ( - msg === 'Share link not found' || - msg === 'Share link not found for this asset' || - msg === 'Asset is not shared' - ) { - return c.json({ error: msg }, 404) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }) .get('/shares/:shareId/fields', async (c) => { @@ -88,14 +97,7 @@ const route = app .map((f) => toFieldInfo(f.field, f.visible)), ) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }) .get( @@ -128,14 +130,7 @@ const route = app return c.json(res) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }, ) @@ -149,14 +144,7 @@ const route = app const asset = await assetService.getAsset({ assetId: fileId }) return c.json(asset) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }) .get( @@ -174,14 +162,7 @@ const route = app const res = await assetService.listComments(targetFileId, req) return c.json(res) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }, ) @@ -253,14 +234,7 @@ const route = app return c.json(comment, 201) } catch (err) { - const msg = (err as Error).message - if (msg === 'Invalid password for share link') { - return c.json({ error: 'Unauthorized' }, 401) - } - if (msg === 'Share link has expired' || msg === 'Share link is disabled') { - return c.json({ error: msg }, 403) - } - return c.json({ error: msg }, 500) + return handlePublicShareError(c, err) } }, ) diff --git a/packages/api/src/share.test.ts b/packages/api/src/share.test.ts index 93d498e9..b29102a4 100644 --- a/packages/api/src/share.test.ts +++ b/packages/api/src/share.test.ts @@ -6,6 +6,7 @@ import { authMiddleware } from './middleware/auth' import { shareService } from '@shumai/core/src/share/share' import { assetService } from '@shumai/core/src/asset/asset' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors' vi.mock('./middleware/auth', () => ({ // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -89,7 +90,7 @@ describe('Share API', () => { updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( - new Error('Invalid password for share link'), + new ShareLinkPasswordInvalidError('Invalid password for share link'), ) const res = await app.request('/shares/share1/info', { @@ -115,7 +116,7 @@ describe('Share API', () => { updatedAt: new Date().toISOString(), }) vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue( - new Error('Share link has expired'), + new ShareLinkExpiredError('Share link has expired'), ) const res = await app.request('/shares/share1/info', { diff --git a/packages/core/src/share/errors.ts b/packages/core/src/share/errors.ts new file mode 100644 index 00000000..10fb0177 --- /dev/null +++ b/packages/core/src/share/errors.ts @@ -0,0 +1,31 @@ +export class ShareLinkNotFoundError extends Error { + constructor(message: string) { + super(message) + this.name = 'ShareLinkNotFoundError' + Object.setPrototypeOf(this, ShareLinkNotFoundError.prototype) + } +} + +export class ShareLinkDisabledError extends Error { + constructor(message: string) { + super(message) + this.name = 'ShareLinkDisabledError' + Object.setPrototypeOf(this, ShareLinkDisabledError.prototype) + } +} + +export class ShareLinkExpiredError extends Error { + constructor(message: string) { + super(message) + this.name = 'ShareLinkExpiredError' + Object.setPrototypeOf(this, ShareLinkExpiredError.prototype) + } +} + +export class ShareLinkPasswordInvalidError extends Error { + constructor(message: string) { + super(message) + this.name = 'ShareLinkPasswordInvalidError' + Object.setPrototypeOf(this, ShareLinkPasswordInvalidError.prototype) + } +} diff --git a/packages/core/src/share/share.ts b/packages/core/src/share/share.ts index a3eb8e1a..9a73bd31 100644 --- a/packages/core/src/share/share.ts +++ b/packages/core/src/share/share.ts @@ -9,6 +9,12 @@ import { } from '@shumai/dtos' import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination' import { getAvatarUrl } from '@shumai/core/src/user/avatar' +import { + ShareLinkNotFoundError, + ShareLinkDisabledError, + ShareLinkExpiredError, + ShareLinkPasswordInvalidError, +} from './errors' export class ShareService { async createShareLink( @@ -143,7 +149,7 @@ export class ShareService { where: { id: shareLinkId }, include: { creator: true }, }) - if (!shareLink) throw new Error('Share link not found') + if (!shareLink) throw new ShareLinkNotFoundError('Share link not found') return await this.toShareLinkInfo(shareLink) } @@ -264,7 +270,7 @@ export class ShareService { ` if (rows.length === 0) { - throw new Error('Asset is not shared') + throw new ShareLinkNotFoundError('Asset is not shared') } const shareRootId = rows[0].shareRootId @@ -273,19 +279,19 @@ export class ShareService { }) if (!shareLink) { - throw new Error('Share link not found for this asset') + throw new ShareLinkNotFoundError('Share link not found for this asset') } if (shareLink.isDisabled) { - throw new Error('Share link is disabled') + throw new ShareLinkDisabledError('Share link is disabled') } if (shareLink.expireAt && shareLink.expireAt < new Date()) { - throw new Error('Share link has expired') + throw new ShareLinkExpiredError('Share link has expired') } if (shareLink.password && shareLink.password !== providedPassword) { - throw new Error('Invalid password for share link') + throw new ShareLinkPasswordInvalidError('Invalid password for share link') } return shareLink