middyjs / middy

🛵 The stylish Node.js middleware engine for AWS Lambda 🛵

Home Page:https://middy.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

http-error-handler : set custom test to return error instead of `statusCode`

throrin19 opened this issue · comments

Is your feature request related to a problem? Please describe.

Others libraries return error with statusCode but their are not HTTP-Errors and return many internal details (example : objection.js with mySqlError)

Actually, it's not possible to change how the test is made to return the error or use custom field/test to go to fallback

Describe the solution you'd like

  • Use directly method isHttpError from http-errors or set a custom function to test if our function is a corect http-error or not
import middy from '@middy/core'
import httpErrorHandler from '@middy/http-error-handler'
import createError from 'http-errors'
import { isHttpError } from 'http-errors'

const lambdaHandler = (event, context) => {
  throw new createError.UnprocessableEntity()
}
export const handler = middy()
    .use(httpErrorHandler({ 
        fallbackMessage : JSON.stringify({ message : 'Internal Server Error' }),
        test: (err) => isHttpError(err)
    }))
    .handler(lambdaHandler)

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Sounds like it would best handled by a custom error handler or a middleware to modify the non-http errors into ones.

Actually, I made this middleware to fix that :

import type { MiddlewareObj } from '@middy/core';

import errorHandler from '@middy/http-error-handler';
import { isHttpError } from 'http-errors';

/**
 * Use @middy/http-error-handler with default error message configured
 */
export const httpErrorMiddleware = (): MiddlewareObj<unknown> => {
    const errorMiddleware = errorHandler({ fallbackMessage : JSON.stringify({ message : 'Internal Server Error' }) });

    return {
        onError : (request) => {
            if (!isHttpError(request.error)) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (request.error as any).expose = false;
            }

            return errorMiddleware.onError?.(request);
        },
    };
};