ATH
ATH
TTCTheo's Typesafe Cult
Created by ATH on 7/14/2023 in #questions
Error Handling through API
Hey peeps, i am building an App with the t3 stack, so far one of the best experiences i've had, was mainly a react native / Expo dev 2 years prior. This is my first exposure to backend development too. The toolchain chosen in t3 makes it easy to get started. but on to my question. I am looking for what's considered best practice regarding error handling. i have a procedure createMember that writes a member to the DB it looks something like this:
create: protectedProcedure
.input(memberSchema)
.mutation(async ({ ctx, input }) => {
try {
const { firstName, lastName, email, role } = input;

const duplicateEmail = await ctx.prisma.member.findFirst({
where: { email: email },
});
if (duplicateEmail) {
throw new TRPCError({
code: "CONFLICT",
message: "Email already in use",
cause: new Error("Email already in use"),
});
}

const userId = ctx.userId;
const member = await ctx.prisma.member.create({
data: {
firstName: firstName,
lastName: lastName,
email: email,
role: role,
createdBy: userId,
orgId: userId,
},
});

return member;
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Error while creating member",
cause: error,
});
}
}),
create: protectedProcedure
.input(memberSchema)
.mutation(async ({ ctx, input }) => {
try {
const { firstName, lastName, email, role } = input;

const duplicateEmail = await ctx.prisma.member.findFirst({
where: { email: email },
});
if (duplicateEmail) {
throw new TRPCError({
code: "CONFLICT",
message: "Email already in use",
cause: new Error("Email already in use"),
});
}

const userId = ctx.userId;
const member = await ctx.prisma.member.create({
data: {
firstName: firstName,
lastName: lastName,
email: email,
role: role,
createdBy: userId,
orgId: userId,
},
});

return member;
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Error while creating member",
cause: error,
});
}
}),
i then expose the error to the client through the onError method on my useCreateMember hook it works just fine. My question is if this is considered "the way" to do it. My Prisma Schema already defines the email as a unique attribute on the member table. So the db should reject no matter the error handling api wise, right? Is there a way to get the DB error through to the client? appreciate the help. thanks all in advance and have a great weekend. XO Alex
9 replies