Skip to content

friendlyError

friendlyError(error: PgErrorLike | null | undefined): string

Translates a pg error into a short message safe to show a user. Never throws; returns MESSAGES.DEFAULT for anything it doesn’t recognize (including a missing code).

import { friendlyError } from '@smplcty/db';
try {
await client.query('insert into users (email) values ($1)', [dupe]);
} catch (err) {
return res.status(400).json({ message: friendlyError(err) });
}
SQLSTATEConstantMessage theme
23505UNIQUE_VIOLATIONalready exists
23503 / 23001FOREIGN_KEY_VIOLATION / RESTRICT_VIOLATIONmissing reference / still referenced
23502NOT_NULL_VIOLATIONrequired field missing
22001STRING_DATA_RIGHT_TRUNCATIONvalue too long
42703UNDEFINED_COLUMNunexpected database error
08000 / 08006 / 08001 / 57P01connection / shutdownservice temporarily unavailable

ERROR_CODES and MESSAGES are exported so you can extend or override individual messages. For a status code alongside the message, use classifyPgError.