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
4 Replies
Dingus Khan
Dingus Khan16mo ago
Hey, I am trying to create the T3 App on my chromebook but the command does not run in terminal, can anyone help please?
vae
vae16mo ago
Why are you posting this on every thread lol
Dingus Khan
Dingus Khan16mo ago
is there a specific thread for this problem?
vae
vae16mo ago
No, but you can make your own! Just click on #questions and make a thread oh you've made one cool 👍
Want results from more Discord servers?
Add your server