Routing-controllers: How to catch custom Error in Koa middleware

Created on 5 Dec 2017  路  11Comments  路  Source: typestack/routing-controllers

Question

Excuse me for my abrupt questions. How can i catch my custom Error in Koa middleware ? Thanks !

Versions

  • koa: ^2.3.0
  • typescript: ^ 2.5.3
  • inversify: ^4.5.2
  • routing-controller: ^0.7.6

myError.ts

import { HttpError } from 'routing-controllers';

export class MyError extends HttpError {

  public args: any[];
  public operationName: string;

  constructor(operationName: string, args: any[] = []) {
      super( 404 );
      Object.setPrototypeOf(this, HttpReqError.prototype);
      this.operationName = operationName;
      this.args = args;
  }

  toJSON( ) {
    return {
      state: this.httpCode,
      failedOperation: this.operationName
    };
  }

myHandlerMiddleware.ts

@injectable( )
export class MyHandlerMiddleware {

  private async use( ctx: Koa.Context, next: ( err?: any ) => Promise< any >): Promise< any > {

    try {
      return next( );
    } catch ( e ) {
      // I cannot catch any error here
      // including the internal error in routing-controllers
      console.log( e );
    }
  }

}

someCtrl.ts

@UseBefore( MyHandlerMiddleware )
@JsonController('/test')
@injectable( )
export class someCtrl {
    @Get('/')
    async test( ) {
        throw new MyError('page not found');
    }
}
awaiting answer question

All 11 comments

You have to write your own custom error handler and disable the default one.

@NoNameProvided Thanks for your reply!

But the link you gave me above has specific rules : Error handlers are specific only to express.

I try the same code, but it is not working in my Koa Server.

How should I catch my custom Error in Koa with my custom middleware or anywhere ? Thanks !

Sadly I am not familiar with Koa. 馃槥

I belive you need to either return await next() or handle errors inside Promise.prototype.catch()'s callback.

@Penggggg, I also want to handle rejected promises by the controller. Not even necessarily only my custom ones. I tried the same approach you described above and failed too.

Have you found a way of doing this in a generic way?

UPDATE: @NoNameProvided any news on that / who else, familiar with Koa could help here out?

I ran into the same issue, not sure how to catch your own errors.

@peterschrott @bramkoot
Have you tried with await?

@injectable( )
export class MyHandlerMiddleware {

  private async use( ctx: Koa.Context, next: ( err?: any ) => Promise< any >): Promise< any > {

    try {
      return await next();
    } catch (e) {
      // you should be able to catch exceptions here
      console.log(e);
    }
  }

}

This should work

import { Context } from "koa";
import { KoaMiddlewareInterface, Middleware } from "routing-controllers";
import { Inject } from "typedi";

@Middleware({type: "before"})
export class ErrorResponder implements KoaMiddlewareInterface {

    public async use(context: Context, next: MiddlewareExecutor) {
        try {
            await next();
        } catch (error) {
            // do something with caught rejection
        }
    }
}

The trick is this middleware "must" be the first middleware to execute because it has to catch any errors rejected from the chain of next() executions from another middlewares and routers.

I have done this and it's working ...

@Middleware({ type: 'before', priority: 50 })
export class ErrorHandlerMiddleware implements KoaMiddlewareInterface {

  public async use(@Ctx() context: Context, next: (err?: any) => Promise<any>): Promise<any> {

    return await next().catch(e => {
      log.error('Unknown error', e);
      return context.throw(500, { error: 'Unknown error' }); 
    });

  }

}

And the creation of the server:

const app = createKoaServer({
  middlewares: [ErrorHandlerMiddleware],
  defaultErrorHandler: false,
});

Stale issue message

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dcbartlett picture dcbartlett  路  3Comments

hellraisercenobit picture hellraisercenobit  路  4Comments

gruckion picture gruckion  路  5Comments

OysteinAmundsen picture OysteinAmundsen  路  3Comments

AnthoniG picture AnthoniG  路  4Comments