fix(db-mongodb): handle duplicate unique index error for DocumentDB (#13239)
Currently, with DocumentDB instead of a friendly error like "Value must be unique" we see a generic "Something went wrong" message. This PR fixes that by adding a fallback to parse the message instead of using `error.keyValue` which doesn't exist for responses from DocumentDB.
This commit is contained in:
@@ -2,6 +2,15 @@ import type { PayloadRequest } from 'payload'
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
function extractFieldFromMessage(message: string) {
|
||||
// eslint-disable-next-line regexp/no-super-linear-backtracking
|
||||
const match = message.match(/index:\s*(.*?)_/)
|
||||
if (match && match[1]) {
|
||||
return match[1] // e.g., returns "email" from "index: email_1"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export const handleError = ({
|
||||
collection,
|
||||
error,
|
||||
@@ -18,20 +27,22 @@ export const handleError = ({
|
||||
}
|
||||
|
||||
// Handle uniqueness error from MongoDB
|
||||
if (
|
||||
'code' in error &&
|
||||
error.code === 11000 &&
|
||||
'keyValue' in error &&
|
||||
error.keyValue &&
|
||||
typeof error.keyValue === 'object'
|
||||
) {
|
||||
if ('code' in error && error.code === 11000) {
|
||||
let path: null | string = null
|
||||
|
||||
if ('keyValue' in error && error.keyValue && typeof error.keyValue === 'object') {
|
||||
path = Object.keys(error.keyValue)[0] ?? ''
|
||||
} else if ('message' in error && typeof error.message === 'string') {
|
||||
path = extractFieldFromMessage(error.message)
|
||||
}
|
||||
|
||||
throw new ValidationError(
|
||||
{
|
||||
collection,
|
||||
errors: [
|
||||
{
|
||||
message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',
|
||||
path: Object.keys(error.keyValue)[0] ?? '',
|
||||
path: path ?? '',
|
||||
},
|
||||
],
|
||||
global,
|
||||
|
||||
Reference in New Issue
Block a user