Fix: Clean username already exists error (#4914)

* Add Prisma unique constraint error messaging.

* Create `_identifyErrorAndFormatMessage` private method for identifying the error type and returning the approprioate error message string
This commit is contained in:
Marcello Fitton
2026-01-29 09:51:03 -08:00
committed by GitHub
parent 49a2b8f6f3
commit b96f38486d

View File

@@ -1,3 +1,4 @@
const { Prisma } = require("@prisma/client");
const prisma = require("../utils/prisma");
const { EventLogs } = require("./eventLogs");
@@ -89,6 +90,16 @@ const User = {
const { password, ...rest } = user;
return { ...rest };
},
_identifyErrorAndFormatMessage: function (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
// P2002 is the unique constraint violation error code
if (error.code === "P2002") {
const target = error.meta?.target;
return `A user with that ${target?.join(", ")} already exists`;
}
}
return error.message;
},
create: async function ({
username,
@@ -121,7 +132,7 @@ const User = {
return { user: this.filterFields(user), error: null };
} catch (error) {
console.error("FAILED TO CREATE USER.", error.message);
return { user: null, error: error.message };
return { user: null, error: this._identifyErrorAndFormatMessage(error) };
}
},
// Log the changes to a user object, but omit sensitive fields
@@ -198,8 +209,11 @@ const User = {
);
return { success: true, error: null };
} catch (error) {
console.error(error.message);
return { success: false, error: error.message };
console.error("FAILED TO UPDATE USER.", error.message);
return {
success: false,
error: this._identifyErrorAndFormatMessage(error),
};
}
},