jeremydaly / lambda-api

Lightweight web framework for your serverless applications
https://serverless-api.com
MIT License
1.41k stars 125 forks source link

Error type names are not preserved when using code bundlers #204

Closed a-game closed 1 year ago

a-game commented 2 years ago

When using lambda-api together with some code bundler like rollup class names are rewritten to avoid duplicates.

The class RouteError will for example be rewritten to something like this:

class RouteError$1 extends Error {
  constructor(message, path) {
    super(message);
    this.name = this.constructor.name;
    this.path = path;
  }
}

The use of this.name = this.constructor.name will make it so that error.name will be "RouteError$1" and not "RouteError"

The result of this is that you can't use the error.name property to check for the error type like mentioned in the docs

Instead you'll have to do some workaround like this:

if (err.name.includes('RouteError')) {
    // do something with route error
  } 

Proposed solution

Simply set the error name to a static string to ensure that it's always the same, like this: this.name = 'RouteError'

ptejada commented 1 year ago

I encountered a similar issue with esbuild where the name attributes are stripped from classes when minimized. I don't know if the linked PR will solve the problem but I propose exporting the error classes instead. So ideally we can do class checking instead of name checking

import { RouteError } from 'lambda-api'

if( err instanceof RouteError ) {
    // Handle route error
}

if anything the exporting of the error might be a bug because the error types are defined in index.d.ts but they are not really exported from the main entry file. If you would use the strategy above then RouteError will be undefined at runtime because it Is just a type reference that your editor can pick up.