prisma-error-formatter
Version:
A flexible and customizable Prisma error formatter to simplify and unify error handling in Prisma Client applications.
44 lines (43 loc) • 1.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatKnownError = formatKnownError;
function formatKnownError(exception) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const messages = [];
switch (exception.code) {
case "P2002":
const target = Array.isArray((_a = exception.meta) === null || _a === void 0 ? void 0 : _a.target)
? (_b = exception.meta) === null || _b === void 0 ? void 0 : _b.target[0]
: "unknown_field";
messages.push({
path: target,
message: `A record with this ${target} already exists.`,
});
break;
case "P2003":
messages.push({
path: ((_c = exception.meta) === null || _c === void 0 ? void 0 : _c.field_name) || "unknown_relation",
message: `Invalid reference: ${(_d = exception.meta) === null || _d === void 0 ? void 0 : _d.field_name}.`,
});
break;
case "P2005":
case "P2006":
messages.push({
path: ((_e = exception.meta) === null || _e === void 0 ? void 0 : _e.field_name) || "unknown_field",
message: `Invalid value for ${(_f = exception.meta) === null || _f === void 0 ? void 0 : _f.field_name}.`,
});
break;
case "P2025":
messages.push({
path: ((_g = exception.meta) === null || _g === void 0 ? void 0 : _g.model_name) || "resource",
message: `The requested ${(_h = exception.meta) === null || _h === void 0 ? void 0 : _h.model_name} does not exist.`,
});
break;
default:
messages.push({
path: "unknown_error",
message: exception.message || "Unknown Prisma error.",
});
}
return messages;
}