#Extending request and error handler

19 messages · Page 1 of 1 (latest)

fallen jewel
#

I dont have any code but i tried that few days ago like what if i have extended the request interface of express for custom properties on request object and now i want to use those properties while i am handling error via a nest error handle which looks like this

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

The ctx response and request i am getting will not include my custom properties right bc it is referring to the express Request interface

narrow pine
#

So how are you wanting to extend the interfaces? Are you wanting to use declaration merging, or are you wanting to make a custom interface that extends them?

#

I personally find the custom interface more explicit, and therefore easier to work with, but then you have to remember it exists instead of just using the exisitng common interface

fallen jewel
#

I was using declaration merging for simplicity for testing like

Import {Request, Response} from "express"

Interface EnhancedRequest extends Request {
Context:string
}

I was unable to get the enhancedResponse via ctx.getrequest @narrow pine

narrow pine
#

context.swtchToHttp().getRequest<EnhancedRequest>()

narrow pine
fallen jewel
fallen jewel
dull gust
narrow pine
fallen jewel
fallen jewel
narrow pine
fallen jewel
#

Mhm

#

Yeah you are using it inside the ctx mhm

#

Prolly _session is an array of obj

#

Damn thanks for the explanation

dull gust
#

Also make sure the express types are installed