2
ContainsNullValuesError,
3
InvalidForeignKeyError,
8
} from '@directus/errors';
9
import type { PostgresError } from './types.js';
11
enum PostgresErrorCodes {
12
FOREIGN_KEY_VIOLATION = '23503',
13
NOT_NULL_VIOLATION = '23502',
14
NUMERIC_VALUE_OUT_OF_RANGE = '22003',
15
UNIQUE_VIOLATION = '23505',
16
VALUE_LIMIT_VIOLATION = '22001',
19
export function extractError(error: PostgresError): PostgresError | Error {
21
case PostgresErrorCodes.UNIQUE_VIOLATION:
22
return uniqueViolation(error);
23
case PostgresErrorCodes.NUMERIC_VALUE_OUT_OF_RANGE:
24
return numericValueOutOfRange(error);
25
case PostgresErrorCodes.VALUE_LIMIT_VIOLATION:
26
return valueLimitViolation(error);
27
case PostgresErrorCodes.NOT_NULL_VIOLATION:
28
return notNullViolation(error);
29
case PostgresErrorCodes.FOREIGN_KEY_VIOLATION:
30
return foreignKeyViolation(error);
36
function uniqueViolation(error: PostgresError) {
37
const { table, detail } = error;
39
const betweenParens = /\(([^)]+)\)/g;
40
const matches = detail.match(betweenParens);
42
if (!matches) return error;
44
const collection = table;
45
const field = matches[0].slice(1, -1);
47
return new RecordNotUniqueError({
53
function numericValueOutOfRange(error: PostgresError) {
54
const regex = /"(.*?)"/g;
55
const matches = error.message.match(regex);
57
if (!matches) return error;
59
const collection = matches[0].slice(1, -1);
62
return new ValueOutOfRangeError({
68
function valueLimitViolation(error: PostgresError) {
71
* Postgres doesn't return the offending column
74
const regex = /"(.*?)"/g;
75
const matches = error.message.match(regex);
77
if (!matches) return error;
79
const collection = matches[0].slice(1, -1);
82
return new ValueTooLongError({
88
function notNullViolation(error: PostgresError) {
89
const { table, column } = error;
90
if (!column) return error;
92
if (error.message.endsWith('contains null values')) {
93
return new ContainsNullValuesError({ collection: table, field: column });
96
return new NotNullViolationError({
102
function foreignKeyViolation(error: PostgresError) {
103
const { table, detail } = error;
105
const betweenParens = /\(([^)]+)\)/g;
106
const matches = detail.match(betweenParens);
108
if (!matches) return error;
110
const collection = table;
111
const field = matches[0].slice(1, -1);
113
return new InvalidForeignKeyError({