Move duplicate key error handling in ORM (#13893)

Error available in REST API
<img width="1360" height="653" alt="Screenshot 2025-08-13 at 11 48 19"
src="https://github.com/user-attachments/assets/a055859d-ce54-4ff6-9aba-fac48e03a98d"
/>

`curl http://localhost:3000/rest/people \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
  "emails": {
    "primaryEmail": "test@test.com"
  }
}'`

closes https://github.com/twentyhq/twenty/issues/13567
This commit is contained in:
Etienne
2025-08-14 18:38:04 +02:00
committed by GitHub
parent 5c61daa201
commit f6d0af5fb8
13 changed files with 156 additions and 50 deletions
@@ -1,12 +1,24 @@
import { t } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
import { QueryFailedError } from 'typeorm';
import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
import { handleDuplicateKeyError } from 'src/engine/api/graphql/workspace-query-runner/utils/handle-duplicate-key-error.util';
import { PostgresException } from 'src/engine/api/graphql/workspace-query-runner/utils/postgres-exception';
import { type ObjectMetadataItemWithFieldMaps } from 'src/engine/metadata-modules/types/object-metadata-item-with-field-maps';
import {
TwentyORMException,
TwentyORMExceptionCode,
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
export const computeTwentyORMException = (error: Error) => {
interface QueryFailedErrorWithCode extends QueryFailedError {
code?: string;
}
export const computeTwentyORMException = (
error: Error,
objectMetadata?: ObjectMetadataItemWithFieldMaps,
) => {
if (error instanceof QueryFailedError) {
if (error.message.includes('Query read timeout')) {
return new TwentyORMException(
@@ -17,6 +29,29 @@ export const computeTwentyORMException = (error: Error) => {
},
);
}
if (
error.message.includes(
'duplicate key value violates unique constraint',
) &&
isDefined(objectMetadata)
) {
return handleDuplicateKeyError(error, objectMetadata);
}
if (error.message.includes('invalid input value for')) {
return new TwentyORMException(
error.message,
TwentyORMExceptionCode.INVALID_INPUT,
);
}
const errorCode = (error as QueryFailedErrorWithCode).code;
if (isDefined(errorCode) && POSTGRESQL_ERROR_CODES.includes(errorCode)) {
throw new PostgresException(error.message, errorCode);
}
throw error;
}
return error;