KoaJs Custom ErrorHandler middleware now working

I want to create an errorHandler middleware for my app. I used KoaJs for my web application and my error basic handler function like that:

error-handler.ts:

import { Context } from "koa";

export const errorHandler : any = (err : Error, ctx : Context ) =>{

    console.log("Something went wrong") ====>>> Its Work
    ctx.status = 403. ========>>>> Not work
    ctx.body = "asdasd" =========>>>> Not work

}

And my endpoint which used error handler like that:

public static async helloWorld(ctx: BaseContext): Promise<void> {
    throw new Error ('Error Here');
}

And my app.js like that:

import Koa from "koa";
import { errorHandler }  from './middleware/error-handler';
...
app.use(errorHandler)
...

And When I send request to endpoint I getting an error like that :

enter image description here

Why Im getting this error? How can I solve this problem?

Upvotes: 0

Views: 737

Answers (1)

Sebastian Hildebrandt
Sebastian Hildebrandt

Reputation: 2771

Your error handler does not work, because you are not catching the error.

Your code works as follows:

As you have a use(errorHandler) and in the error handler no await next(), your complete error handler is executed first (no matter if there is an error or not). Then your helloWorld function is executed. And as there is an uncatched error, Koa does reply a 404 not found to the client.

How it should be:

Your errorHandler should have a await next(), then afterwards it needs to check if there is an error. If yes, then this needs to be captured and then you can specify status code and resulting body.

Possible solution:

I guess your errorHandler should look more like this:

export const errorHandler : any = async (ctx : Context, next ) =>{
    try {
      await next();
    } catch (err) {
      console.log("Something went wrong");
      ctx.status = 403;
      ctx.body = err;
    }
}

Upvotes: 1

Related Questions