#middleware response 200 for thrown HTTP Error ?!?

2 messages · Page 1 of 1 (latest)

oblique trout
#

can someone please explain why the response object's status code returns a 200 in this middleware when i am clearly throwing a 500? the 500 is also being shown in my http client...ive created a brand new nestjs project with just the following

// this is the entire logger middleware
import { Logger, NestMiddleware } from "@nestjs/common";
import { NextFunction, Request, Response } from "express";

export class HttpLoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger("HTTP");

  use(req: Request, res: Response, next: NextFunction) {
    const timestamp = new Date().toISOString();
    this.logger.log(`Logging request: ${req.method} ${req.url} ${res.statusCode} ${timestamp}`);
    return next();
  }
}
// the request to trigger the error
import { Controller, Get, InternalServerErrorException } from "@nestjs/common";
import { AppService } from "./app.service";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    throw new InternalServerErrorException("sigh...");
  }
}

when i hit getHello endpoint, the nest logger outputs

LOG [HTTP] Logging request: GET / 200 2023-09-17T07:44:58.330Z

Can someone explain this to me like im 5 why this middleware is returning a 200 status code before i throw a 5 year old tantrum and throw my computer out the window?

molten knot
#

res.status hasn't been set to the 500 by the time the middleware is called.