From b411218a3e83e1c5f322a11e033797996d321ce7 Mon Sep 17 00:00:00 2001 From: Michael Dausmann Date: Sat, 3 Jun 2023 23:01:46 +1000 Subject: [PATCH] FIX: exceeding Notes limit should be a 401 not 500 --- lib/services/errors.ts | 6 ++++++ lib/services/notes.service.ts | 3 ++- server/trpc/trpc.ts | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 lib/services/errors.ts diff --git a/lib/services/errors.ts b/lib/services/errors.ts new file mode 100644 index 0000000..d163de8 --- /dev/null +++ b/lib/services/errors.ts @@ -0,0 +1,6 @@ +export class AccountLimitError extends Error { + constructor(message: string) { + super(message); + Object.setPrototypeOf(this, AccountLimitError.prototype); + } +} \ No newline at end of file diff --git a/lib/services/notes.service.ts b/lib/services/notes.service.ts index f572da2..5865aa7 100644 --- a/lib/services/notes.service.ts +++ b/lib/services/notes.service.ts @@ -1,5 +1,6 @@ import prisma_client from '~~/prisma/prisma.client'; import { openai } from './openai.client'; +import { AccountLimitError } from './errors'; export default class NotesService { async getAllNotes() { @@ -21,7 +22,7 @@ export default class NotesService { }); if(account.notes.length>= account.max_notes){ - throw new Error('Note Limit reached, no new notes can be added'); + throw new AccountLimitError('Note Limit reached, no new notes can be added'); } return prisma_client.note.create({ data: { account_id, note_text }}); diff --git a/server/trpc/trpc.ts b/server/trpc/trpc.ts index 0c284ee..cff0e19 100644 --- a/server/trpc/trpc.ts +++ b/server/trpc/trpc.ts @@ -11,9 +11,24 @@ import { initTRPC, TRPCError } from '@trpc/server' import { Context } from './context'; import { ACCOUNT_ACCESS } from '~~/prisma/account-access-enum'; import superjson from 'superjson'; +import { AccountLimitError } from '~~/lib/services/errors'; const t = initTRPC.context().create({ transformer: superjson, + errorFormatter: (opts)=> { + const { shape, error } = opts; + if (!(error.cause instanceof AccountLimitError)) { + return shape; + } + return { + ...shape, + data: { + ...shape.data, + httpStatus: 401, + code: 'UNAUTHORIZED' + }, + }; + } }) /**