Middy Unexpected Behavior in middleware execuation order

62 views Asked by At

Hey I am trying to write a custom middleware with middy. Please take a look at the code below, I am clearly calling httpErrorHandler before customMiddleware, but still httpErrorHandler is able to handle the error thrown from customMiddleware, how is this happening, aren't middlewares expected to execute in a specified order.?

I can affirm that httpErrorHandler is indeed handling the error, because when I do not call it, the function simply yields a generic 500 internal server error response, irrespective of the fact that I am triggering a 401 Unauthorized error. Why is this occurring, given the expected sequential execution of middleware?

import middy from '@middy/core';
import {createError} from '@middy/util'
import httpErrorHandler from '@middy/http-error-handler';

function customMiddleware() {
    return {
        before: async (request) => {
            throw createError(401, "Not Authorized")
        }
    }
}

async function testAuth(event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify({
        message: "Hello from testAuth function"
    })
  }
}

export const handler = middy(testAuth)
    .use(httpErrorHandler())
    .use(customMiddleware())

0

There are 0 answers