MCPcopy
hub / github.com/sequelize/sequelize / formatError

Method formatError

lib/dialects/mysql/query.js:211–269  ·  view source on GitHub ↗
(err, errStack)

Source from the content-addressed store, hash-verified

209 }
210
211 formatError(err, errStack) {
212 const errCode = err.errno || err.code;
213
214 switch (errCode) {
215 case ER_DUP_ENTRY: {
216 const match = err.message.match(/Duplicate entry '([\s\S]*)' for key '?((.|\s)*?)'?$/);
217 let fields = {};
218 let message = 'Validation error';
219 const values = match ? match[1].split('-') : undefined;
220 const fieldKey = match ? match[2].split('.').pop() : undefined;
221 const fieldVal = match ? match[1] : undefined;
222 const uniqueKey = this.model && this.model.uniqueKeys[fieldKey];
223
224 if (uniqueKey) {
225 if (uniqueKey.msg) message = uniqueKey.msg;
226 fields = _.zipObject(uniqueKey.fields, values);
227 } else {
228 fields[fieldKey] = fieldVal;
229 }
230
231 const errors = [];
232 _.forOwn(fields, (value, field) => {
233 errors.push(new sequelizeErrors.ValidationErrorItem(
234 this.getUniqueConstraintErrorMessage(field),
235 'unique violation', // sequelizeErrors.ValidationErrorItem.Origins.DB,
236 field,
237 value,
238 this.instance,
239 'not_unique'
240 ));
241 });
242
243 return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields, stack: errStack });
244 }
245
246 case ER_ROW_IS_REFERENCED:
247 case ER_NO_REFERENCED_ROW: {
248 // e.g. CONSTRAINT `example_constraint_name` FOREIGN KEY (`example_id`) REFERENCES `examples` (`id`)
249 const match = err.message.match(
250 /CONSTRAINT ([`"])(.*)\1 FOREIGN KEY \(\1(.*)\1\) REFERENCES \1(.*)\1 \(\1(.*)\1\)/
251 );
252 const quoteChar = match ? match[1] : '`';
253 const fields = match ? match[3].split(new RegExp(`${quoteChar}, *${quoteChar}`)) : undefined;
254
255 return new sequelizeErrors.ForeignKeyConstraintError({
256 reltype: String(errCode) === String(ER_ROW_IS_REFERENCED) ? 'parent' : 'child',
257 table: match ? match[4] : undefined,
258 fields,
259 value: fields && fields.length && this.instance && this.instance[fields[0]] || undefined,
260 index: match ? match[2] : undefined,
261 parent: err,
262 stack: errStack
263 });
264 }
265
266 default:
267 return new sequelizeErrors.DatabaseError(err, { stack: errStack });
268 }

Callers 1

runMethod · 0.95

Calls 1

Tested by

no test coverage detected