Question
Excuse me for my abrupt questions. How can i catch my custom Error in Koa middleware ? Thanks !
Versions
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');
}
}
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.