UNPKG

adminjs

Version:
72 lines (70 loc) 1.97 kB
import AppError from '../../utils/errors/app-error.js'; import ForbiddenError from '../../utils/errors/forbidden-error.js'; import NotFoundError from '../../utils/errors/not-found-error.js'; import ValidationError from '../../utils/errors/validation-error.js'; /** * @private * @classdesc * Function which catches all the errors thrown by the action hooks or handler */ const actionErrorHandler = (error, context) => { if (error instanceof ValidationError || error instanceof ForbiddenError || error instanceof NotFoundError || error instanceof AppError) { const { record, currentAdmin, action } = context; const baseError = error.baseError ?? null; let baseMessage = ''; let errors = {}; let meta; let notice; if (error instanceof ValidationError) { baseMessage = error.baseError?.message || 'thereWereValidationErrors'; errors = error.propertyErrors; } else { // ForbiddenError, NotFoundError, AppError baseMessage = error.baseMessage || 'anyForbiddenError'; } // Add required meta data for the list action if (action.name === 'list') { meta = { total: 0, perPage: 0, page: 0, direction: null, sortBy: null }; } const recordJson = record?.toJSON?.(currentAdmin); if (error instanceof ForbiddenError && recordJson) { recordJson.params = {}; recordJson.title = ''; recordJson.populated = {}; } notice = { message: baseMessage, type: 'error' }; if (error instanceof AppError && error.notice) { notice = { ...notice, ...error.notice }; } return { record: { ...recordJson, params: recordJson?.params ?? {}, populated: recordJson?.populated ?? {}, baseError, errors }, records: [], notice, meta }; } throw error; }; export default actionErrorHandler;