routing-controllers icon indicating copy to clipboard operation
routing-controllers copied to clipboard

feature: Add interface to override routing-controllers' default error handler

Open GeekEast opened this issue 2 years ago • 1 comments

Description

Currently routing-controllers' defaultErrorHandler is enabled by default.

If I want to do some error logging and error filtering using middleware, it can only happen after the error is sent to the client.

error filtering example

if (error instanceof JsonWebTokenError) return next(new UnauthorizedError(error.message))

I tried this approach

  • turn off defaultErrorHandler
  • write my own custom error handler middleware

But I got some issues:

  • I cannot confirm that the error throw behavior is the same as before.

So I tried to replicate the default error handler, but I find it's quite complicated to override since it's not easy to get the actionMetadata object in middleware.

Proposed solution

I would suggest providing an interface like this to override the default error handler.

export class CustomErrorHandler {
     handle(error:any, action: ActionMetadata | undefined, options: Action){
          // developer can customer behaviours here.
     }
}

GeekEast avatar Aug 30 '21 00:08 GeekEast

If you add your own error handler it is quite different. You are basically registering a normal ExpressErrorMiddlewareInterface by using your own. The downside is of course you have no access to the action and options.

A possible solution would be to extend the thrown error by the metadata required for the default error handler and pass that to the custom error handler instead. We could create a new base class for errors with the processJsonError and processTextError methods included. That way the users can just use the built in stuff even in their custom error handlers if they choose to.

@NoNameProvided What do you think?

attilaorosz avatar Feb 19 '22 08:02 attilaorosz