refactor(create-config): move unique violation error handling to error-handler
This commit is contained in:
@@ -1,9 +1,13 @@
|
||||
import logger from './logger.js';
|
||||
import objection from 'objection';
|
||||
import * as Sentry from './sentry.ee.js';
|
||||
const { NotFoundError, DataError, ValidationError } = objection;
|
||||
const { NotFoundError, DataError, ValidationError, UniqueViolationError } =
|
||||
objection;
|
||||
import HttpError from '../errors/http.js';
|
||||
import { renderObjectionError } from './renderer.js';
|
||||
import {
|
||||
renderObjectionError,
|
||||
renderUniqueViolationError,
|
||||
} from './renderer.js';
|
||||
|
||||
// Do not remove `next` argument as the function signature will not fit for an error handler middleware
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
@@ -20,6 +24,10 @@ const errorHandler = (error, request, response, next) => {
|
||||
renderObjectionError(response, error, 422);
|
||||
}
|
||||
|
||||
if (error instanceof UniqueViolationError) {
|
||||
renderUniqueViolationError(response, error);
|
||||
}
|
||||
|
||||
if (error instanceof DataError) {
|
||||
response.status(400).end();
|
||||
}
|
||||
|
@@ -64,16 +64,31 @@ const renderError = (response, errors, status, type) => {
|
||||
return response.status(errorStatus).send(payload);
|
||||
};
|
||||
|
||||
const renderUniqueViolationError = (response, error) => {
|
||||
const errors = error.columns.map((column) => ({
|
||||
[column]: [`'${column}' must be unique.`],
|
||||
}));
|
||||
|
||||
return renderError(response, errors, 422, 'UniqueViolationError');
|
||||
};
|
||||
|
||||
const renderObjectionError = (response, error, status) => {
|
||||
const { statusCode, type, data = {} } = error;
|
||||
|
||||
const computedStatusCode = status || statusCode;
|
||||
|
||||
const computedErrors = Object.entries(data).map(([fieldName, fieldErrors]) => ({
|
||||
[fieldName]: fieldErrors.map(({ message }) => message)
|
||||
}));
|
||||
const computedErrors = Object.entries(data).map(
|
||||
([fieldName, fieldErrors]) => ({
|
||||
[fieldName]: fieldErrors.map(({ message }) => message),
|
||||
})
|
||||
);
|
||||
|
||||
return renderError(response, computedErrors, computedStatusCode, type);
|
||||
};
|
||||
|
||||
export { renderObject, renderError, renderObjectionError };
|
||||
export {
|
||||
renderObject,
|
||||
renderError,
|
||||
renderObjectionError,
|
||||
renderUniqueViolationError,
|
||||
};
|
||||
|
Reference in New Issue
Block a user