Returning error from custom lambda custom middleware

1.7k Views Asked by At

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

2

There are 2 best solutions below

0
On

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:

Argument of type 'MiddlewareObj<any, any, Error, Context>' is not assignable to parameter of type 'MiddlewareObject<APIGatewayProxyEvent, ResponsePayload, Context>'.Types of property 'before' are incompatible.
1
On

I think you're looking for createHttpError from @middy/http-error-handler. Alternatively, you can create a wrapper for this—maybe call it createError()—and throw. documentation