for the last 3-4 hours i've been trying to correctly return error from custom @middy middleware unsuccessfully
export const middyfy = (handler: any) => {
return middy(handler).use(middyJsonBodyParser());
};
export const authorizedMiddify = (handler: any) => {
return middyfy(handler)
.use(httpHeaderNormalizer())
.use(httpErrorHandler())
.use({
before: (request, next) => {
console.log(3)
throw createError(401, 'Unauthorized');
}
});
};
this logs:
{
body: 'Unauthorized',
headers: { 'Content-Type': 'text/plain' },
statusCode: 401
}
and in postman i receive empty body and 502 error.
what is wrong here? P.S: createError is from @middy/util
TL;DR: might be wrong middy package.
I have encountered the same error as you. Although I don't know the exact package that you used.
I fixed mine by using @middy/core instead of just middy. It is not noticeable in plain JS, but in Typescript there is a type error for the
middy(handler).use(httpErrorHandler())
, this might be the reason why it is throwing a 502 error because httpErrorHandler is an incompatible middleware.Type Error: