diff --git a/packages/core/strapi/src/middlewares/errors.ts b/packages/core/strapi/src/middlewares/errors.ts index 5928d84495..0c566a47a7 100644 --- a/packages/core/strapi/src/middlewares/errors.ts +++ b/packages/core/strapi/src/middlewares/errors.ts @@ -3,6 +3,28 @@ import type { Common } from '@strapi/types'; import { formatApplicationError, formatHttpError, formatInternalError } from '../services/errors'; +// NOTE: The error.name check is not necessary in the v5 branch! +// Therefore it should be considered a hack workaround for an actual bug which means that there is a bug +// somewhere else in the code. +// The issue is most likely somewhere where ValidationErrors are being created that are not +// instanceof errors.ApplicationError despite actually being ApplicationErrors. +// +// This code is only included because v4 is in maintenance mode and this is a safe fix, but does not solve the +// root cause of the problem. +export function isErrorOfTypeOrSubclass( + error: any, + constructor: { new (...args: any[]): T } +): error is T { + let proto = error?.constructor; + while (proto) { + if (proto.name === constructor.name) { + return true; + } + proto = Object.getPrototypeOf(proto); + } + return false; +} + const errorMiddleware: Common.MiddlewareFactory = (/* _, { strapi } */) => { return async (ctx, next) => { try { @@ -12,14 +34,14 @@ const errorMiddleware: Common.MiddlewareFactory = (/* _, { strapi } */) => { return ctx.notFound(); } } catch (error) { - if (error instanceof errors.ApplicationError) { + if (isErrorOfTypeOrSubclass(error, errors.ApplicationError)) { const { status, body } = formatApplicationError(error); ctx.status = status; ctx.body = body; return; } - if (error instanceof errors.HttpError) { + if (isErrorOfTypeOrSubclass(error, errors.HttpError)) { const { status, body } = formatHttpError(error); ctx.status = status; ctx.body = body;