#Throwing new HTTP Exception in NestJS and Fastify results in an error

4 messages · Page 1 of 1 (latest)

proud arrow
#

I'm currently trying to learn NestJS and came across this error while throwing an exception inside a middleware. Why does this happen?

Code:

import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
import { IncomingMessage, ServerResponse } from 'http';

@Injectable()
export class ExampleMiddleware implements NestMiddleware {
  use(req: IncomingMessage, res: ServerResponse, next: Function) {
    const { authorization } = req.headers;
    if (!authorization) throw new HttpException('No Authorization Token', HttpStatus.FORBIDDEN);
    else if (authorization === 'password') next();
    else throw new HttpException('Incorrect Authorization Token', HttpStatus.FORBIDDEN);
  }
}

Error:

/home/api/node_modules/fastify/lib/reply.js:479
  if (reply[kRouteContext].preSerialization !== null) {
                           ^
TypeError: Cannot read properties of undefined (reading 'preSerialization')```
proud arrow
#

Oh am I supposed to use Guards instead of MIddleware?

north elm
#

I would avoid using middleware unless you really need to, especially with fastify. Fastify has a compatibility layer with express middleware, but it's not perfect

proud arrow
#

Ok