/prisma-6:preventing-error-exposurefrom prisma-6
Prevent leaking database errors and P-codes to clients. Use when implementing API error handling or user-facing error messages.
Ships in prisma-6. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill teaches Claude how to handle Prisma errors securely by transforming detailed database errors into user-friendly messages while preserving debugging information in logs.
Security Risk: Exposing this information helps attackers:
Solution Pattern: Transform errors for clients, log full details server-side.
Key capabilities:
Phase 1: Error Detection
Phase 2: Error Transformation
Phase 3: Response and Logging
Development Environment:
Production Environment:
Next.js App Router:
export async function POST(request: Request) {
try {
const data = await request.json()
const result = await prisma.user.create({ data })
return Response.json(result)
} catch (error) {
return handlePrismaError(error)
}
}
Express/Fastify:
app.use((err, req, res, next) => {
if (isPrismaError(err)) {
const { status, message, errorId } = transformPrismaError(err)
logger.error({ err, errorId, userId: req.user?.id })
return res.status(status).json({ error: message, errorId })
}
next(err)
})
## Example 1: Error Transformation Function
Pattern: P-code to User Message
import { Prisma } from '@prisma/client'
function transformPrismaError(error: unknown) {
const errorId = crypto.randomUUID()
if (error instanceof Prisma.PrismaClientKnownRequestError) {
switch (error.code) {
case 'P2002':
return {
status: 409,
message: 'A record with this information already exists.',
errorId,
logDetails: {
code: error.code,
meta: error.meta,
target: error.meta?.target
}
}
case 'P2025':
return {
status: 404,
message: 'The requested resource was not found.',
errorId,
logDetails: {
code: error.code,
meta: error.meta
}
}
case 'P2003':
return {
status: 400,
message: 'The provided reference is invalid.',
errorId,
logDetails: {
code: error.code,
meta: error.meta,
field: error.meta?.field_name
}
}
case 'P2014':
return {
status: 400,
message: 'The change violates a required relationship.',
errorId,
logDetails: {
code: error.code,
meta: error.meta
}
}
default:
return {
status: 500,
message: 'An error occurred while processing your request.',
errorId,
logDetails: {
code: error.code,
meta: error.meta
}
}
}
}
if (error instanceof Prisma.PrismaClientValidationError) {
return {
status: 400,
message: 'The provided data is invalid.',
errorId,
logDetails: {
type: 'ValidationError',
message: error.message
}
}
}
return {
status: 500,
message: 'An unexpected error occurred.',
errorId,
logDetails: {
type: error?.constructor?.name,
message: error instanceof Error ? error.message : 'Unknown error'
}
}
}
Pattern: Middleware with Logging
import { Prisma } from '@prisma/client'
import { logger } from './logger'
export function handlePrismaError(error: unknown, context?: Record<string, unknown>) {
const { status, message, errorId, logDetails } = transformPrismaError(error)
logger.error({
errorId,
...logDetails,
context,
stack: error instanceof Error ? error.stack : undefined,
timestamp: new Date().toISOString()
})
return {
status,
body: {
error: message,
errorId
}
}
}
export async function createUser(data: { email: string; name: string }) {
try {
return await prisma.user.create({ data })
} catch (error) {
const { status, body } = handlePrismaError(error, {
operation: 'createUser',
email: data.email
})
throw new ApiError(status, body)
}
}
Pattern: Development vs Production
const isDevelopment = process.env.NODE_ENV === 'development'
function formatErrorResponse(error: unknown, errorId: string) {
const { status, message, logDetails } = transformPrismaError(error)
const baseResponse = {
error: message,
errorId
}
if (isDevelopment && error instanceof Prisma.PrismaClientKnownRequestError) {
return {
...baseResponse,
debug: {
code: error.code,
meta: error.meta,
clientVersion: Prisma.prismaVersion.client
}
}
}
return baseResponse
}
Pattern: P2002 Constraint Details
function extractP2002Details(error: Prisma.PrismaClientKnownRequestError) {
if (error.code !== 'P2002') return null
const target = error.meta?.target as string[] | undefined
if (!target || target.length === 0) {
return 'A record with this information already exists.'
}
const fieldMap: Record<string, string> = {
email: 'email address',
username: 'username',
phone: 'phone number',
slug: 'identifier'
}
const fieldName = target[0]
const friendlyName = fieldMap[fieldName] || 'information'
return `A record with this ${friendlyName} already exists.`
}
function transformPrismaError(error: unknown) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
const message = extractP2002Details(error)
return {
status: 409,
message,
errorId: crypto.randomUUID(),
logDetails: { code: 'P2002', target: error.meta?.target }
}
}
}
## Error Response Format
Client Response (JSON):
{
"error": "User-friendly message without database details",
"errorId": "uuid-for-correlation"
}
Server Log (Structured):
{
"level": "error",
"errorId": "uuid-for-correlation",
"code": "P2002",
"meta": { "target": ["email"] },
"context": { "operation": "createUser", "userId": "123" },
"stack": "Error stack trace...",
"timestamp": "2025-11-21T10:30:00Z"
}
Development Response (Optional Debug):
{
"error": "User-friendly message",
"errorId": "uuid-for-correlation",
"debug": {
"code": "P2002",
"meta": { "target": ["email"] },
"clientVersion": "6.0.0"
}
}
## Security Requirements
MUST:
SHOULD:
NEVER:
P2002 - Unique constraint violation
P2025 - Record not found
P2003 - Foreign key constraint violation
P2014 - Required relation violation
P2024 - Connection timeout
After implementing error handling:
Verify No P-codes Exposed:
Confirm Logging Works:
Test Error Scenarios:
Review Environment Behavior:
Error exposure prevention works with input validation:
Input Validation (SECURITY-input-validation skill):
Error Transformation (this skill):
Pattern:
async function createUser(input: unknown) {
const validation = userSchema.safeParse(input)
if (!validation.success) {
return {
status: 400,
body: {
error: 'Invalid user data',
fields: validation.error.flatten().fieldErrors
}
}
}
try {
return await prisma.user.create({ data: validation.data })
} catch (error) {
const { status, body } = handlePrismaError(error)
return { status, body }
}
}
Validation catches format issues, error transformation handles database constraints.
Error Handling and Validation:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
19 skills in this plugin
/configuring-connection-poolsConfigure connection pool sizing for optimal performance. Use when configuring DATABASE_URL or deploying to production./configuring-serverless-clientsConfigure PrismaClient for serverless (Next.js, Lambda, Vercel) with connection_limit=1 and global singleton pattern./configuring-transaction-isolationConfigure transaction isolation levels to prevent race conditions and handle concurrent access. Use when dealing with concurrent updates, financial operations, inventory management, or when users mention race conditions, dirty reads, phantom reads, or concurrent modifications./creating-client-singletonsPrevent multiple PrismaClient instances that exhaust connection pools causing P1017 errors. Use when creating PrismaClient, exporting database clients, setting up Prisma in new files, or encountering connection pool errors. Critical for serverless environments./deploying-production-migrationsDeploy migrations to production safely using migrate deploy in CI/CD. Use when setting up production deployment pipelines./ensuring-query-type-safetyUse Prisma's generated types, `Prisma.validator`, and `GetPayload` for type-safe queries.npx claudepluginhub djankies/claude-configs --plugin prisma-6