Iliaaaa
Iliaaaa

Reputation: 109

Returning error from custom lambda custom middleware

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

Upvotes: 0

Views: 2134

Answers (3)

Daniel Albert
Daniel Albert

Reputation: 76

If I don't have {disableContentTypeError:true} I also get a content type error if the request is not a post and the body of the request is empty. Hopefully this helps someone that is getting the content type error.

import middy from '@middy/core'
import httpHeaderNormalizer from '@middy/http-header-normalizer'
import httpJsonBodyParser from '@middy/http-json-body-parser'
import httpErrorHandler from '@middy/http-error-handler'

export const middlewares = {
    standardMiddleware: middy().use([httpHeaderNormalizer(), httpJsonBodyParser({disableContentTypeError:true}), httpErrorHandler()])
}

Upvotes: 0

rxrosli
rxrosli

Reputation: 43

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.

Upvotes: 0

cphytia
cphytia

Reputation: 1

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

Upvotes: 0

Related Questions