Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following manner:

@Catch(UserNotFoundException)
export class UserNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: UserNotFoundException, host: ArgumentsHost) {
    const errorResponse = new ErrorResponse<string[]>();
    const response = host.switchToHttp().getResponse();
    errorResponse.message = 'unauthorized exception'
    errorResponse.errors = [
      'invalid username or password'
    ];
    response.status(401).json(errorResponse)

  }
}

However, I keep encountering the error message "response.status(...).json() is not a function."

[Nest] 5400   - 05/17/2020, 00:27:26   [ExceptionsHandler] response.status(...).json is not a function +82263ms
TypeError: response.status(...).json is not a function

I understand that I need to specify the type of response writer (e.g., Response from Express).

To address this issue, I attempted importing the Response object from Express and updating the type of the response variable as follows:

import {Response} from 'express';
 const response = host.switchToHttp().getResponse<Response>();

After making these changes, everything worked smoothly. However, I prefer not to introduce Express elements into my NestJS Fastify application. Is there an alternative class that can replace the Express Response object? Any suggestions for a more elegant solution would be greatly appreciated.

Thank you all.

Answer №1

When working with Fastify, it is important to utilize the

FastifyReply<ServerResponse>
type from the fastify and http packages. Unlike some other frameworks, Fastify itself does not have a built-in json method on the reply object. Instead, you can use the .send() method which will automatically serialize an object into JSON format if given an object.

If you attempt to use the Response object from express in your project, it may build successfully but you are likely to encounter a runtime error stating that response.status().json is not a function. The recommended approach is shown below:

import { FastifyReply } from 'fastify';

@Catch(UserNotFoundException)
export class UserNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: UserNotFoundException, host: ArgumentsHost) {
    const errorResponse = new ErrorResponse<string[]>();
    const response = host.switchToHttp().getResponse<FastifyReply<ServerResponse>>();
    errorResponse.message = 'unauthorized exception'
    errorResponse.errors = [
      'invalid username or pass'
    ];
    response.status(401).send(errorResponse)

  }
}

In general, Nest acts as a bridge for Express and Fastify, and most of the documentation focuses on Express-specific options like Request and Response. When looking for details on library-specific approaches, it is advisable to consult Fastify's documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing parameters to an external function in order to display a message is proving difficult. An error of type TypeError is being encountered, specifying that the Class constructor AlertMessage cannot be called without using the

Every time I attempt to pass a message as an argument to the showAlert() function, an error is triggered: Error: An instance of the AlertMessage class cannot be created without using 'new' image: https://i.sstatic.net/d0GGD.jpg I am simply tryi ...

The output from the Node.js child_process.exec command returned null for stdout, yet stderr was not empty

I'm currently working with a simple code that runs java -version in the command line to check if Java is installed on the user's system. Interestingly, when I execute this code, the stdout does not display anything, but the stderr shows the expe ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

Updating inner text content dynamically can be accomplished without relying on the use of the eval() function

I am faced with a situation where I have multiple batches of code structured like this: 1 <div id="backgrounds" class="centery">Backgrounds 2 <div id="bk1" class="attr">Background 1 3 <div class="container"> 4 ...

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

How can you effectively load shared header and panel HTML onto pages located in separate directories using jQuery Mobile?

I am currently developing a multi-page application utilizing jQuery Mobile and incorporating loadPage() to retrieve various pages. The overall structure is outlined below. landing.html /app-pages/page1.html /app-pages/page2.html /app-pages/page3.html ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

Override the default HTML style overflow to hidden with Material UI Swipable Drawer

Currently, I'm utilizing the Material UI SwipableDrawer component which has an unexpected drawback of causing the scrollbar to disappear when the drawer is displayed. This issue overrides my specified style of "overflow-y: scroll" on the Html tag and ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

Incorporating the JQuery plugin Lightbox_me into a Ruby on Rails application

Greetings! I am currently attempting to incorporate a popup window using the Lightbox_me plugin in my Ruby On Rails application. After downloading jquery.lightbox_me.js and placing it in the app/assets/javascripts directory, I added //= require jquery.lig ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

What reasons could lead to useSWR returning undefined even when fallbackData is provided?

In my Next.js application, I'm utilizing useSWR to fetch data on the client-side from an external API based on a specified language query parameter. To ensure the page loads initially, I retrieve data in a default language in getStaticProps and set it ...

Mastering Authentication in React JS: Best Practices

I am currently working on integrating Backend (Express JS) and Frontend (React JS). One of the challenges I am facing is understanding how to manage sessions effectively. When a user logs in using a form built with React JS, the backend responds with a HS ...

Utilizing AJAX, a PHP script creates an HTML table that allows users to easily perform actions such as deleting, updating

I'm a beginner in the world of ajax and I am eager to utilize it with php in order to develop a table that can be edited by users directly on the webapp interface. Here's my current progress... PHP class genTable{ public function table1(){ ...

Creating a component with @input for unit tests in Angular can be achieved through the following steps

I'm encountering issues while attempting to create a testing component with an @input. The component utilizes properties from the feedback model, and although I imported them into the test file, errors are being displayed. Can anyone offer assistance? ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...

Tips for designing a three-dimensional egg shape using Three.js?

I'm looking to create a unique egg shape using Three.js, but I seem to be missing the correct equation. Below is the code I currently have, utilizing LatheGeometry. Can anyone provide some guidance? var r0 = 40 var r1 = r0/4; var inc = Math.PI/r0; po ...

Single quotation mishap in JSON

How can I successfully send JSON data that contains single quotes without encountering errors? I need to include values with single quotes, but how can I do this without causing any issues? $.ajax({ type: "post", url: "canliAyarlari.aspx/dosyaYa ...