Generating custom error messages with specified format when utilizing routing-controllers

I'm currently working on a Node APP that utilizes the routing-controllers library. In the README file, there is a section titled Throw HTTP errors, which includes a self-explanatory example.

However, I encountered an issue when attempting to replicate the code. Here is the example I have in my own code (for testing purposes, I want to trigger the exception without any further action):

@Post('/')
async post(): Promise<any> {
    throw new NotFoundError(`User was not found.`);
}

In this code snippet, the NotFoundError is imported from the routing-controllers library. It should work as intended but instead of returning an object like this:

{
  "name": "NotFoundError",
  "message": "User was not found."
}

The response returns the entire error trace rather than just the specified object. The status code is 404, but the text returned is lengthy and shows various steps within the error trace.

Error
    at new HttpError (/path_to_the_code/node_modules/src/http-error/HttpError.ts:16:18)
    at new NotFoundError (/path_to_the_code/node_modules/src/http-error/NotFoundError.ts:10:5)
    at HelloWorld.<anonymous> (/path_to_the_code/src/controller/controllers/HelloWorldController.ts:20:15)
    ...

I've been trying to debug this issue, but it seems that line 13:12 points to another route implementation:

@Get('/')
async get(): Promise<any> {
    return this.helloWorldService.getHello()
}

For reference, here is the full controller implementation:

import { Controller, Get, NotFoundError, Post } from 'routing-controllers';
import { Service } from 'typedi';
import { HelloWorldService } from '../../business/services/HelloWorldService';

@Service()
@Controller('/hello-world')
export class HelloWorld {

    constructor(public helloWorldService: HelloWorldService) { }

    @Get('/')
    async get(): Promise<any> {
        return this.helloWorldService.getHello()
    }

    @Post('/')
    async post(): Promise<any> {
        throw new NotFoundError(`User was not found.`);
    }
}

It's puzzling to me where exactly this error is originating from...

My goal is to receive the same structured response from the server as depicted in the documentation: {name:'', message:''}, and not the complete stack trace information.

Despite the functionality appearing to work fine with regards to the HTTP code itself, there seems to be an internal error causing the unexpected behavior.

Thank you in advance for any insights or assistance.

Answer №1

As a newcomer to using Express and routing-controllers, I have implemented a solution that may not be the most optimal. My approach involved incorporating a custom error handler as middleware:

import { Middleware, ExpressErrorMiddlewareInterface, HttpError } from 'routing-controllers';

@Middleware({ type: 'after' })
export class HttpErrorHandler implements ExpressErrorMiddlewareInterface {
    error(error: any, request: any, response: any, next: (err: any) => any) {
        if (error instanceof HttpError) {
            response.status(error.httpCode).json(error);
        }

        next(error);
    }
}

It's worth noting that I utilized error.httpCode to set the status and then converted error to JSON format. Subsequently, I included the error handler in the middlewares array while setting defaultErrorHandler to false:

const app = createExpressServer({
    defaultErrorHandler: false,
    middlewares: [
        HttpErrorHandler
    ],
    // ...
});

Following these modifications, my responses now include relevant status codes such as the following example:

{
   httpCode: 404,
   name: "NotFoundError",
   message: "User was not found",
}

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

Tips for enhancing express.Request using tsserver and JSDoc

Recently, I have been utilizing tsserver with JSDoc in vim while working on a JavaScript project. Unfortunately, I've encountered an issue that needs resolving: /** @type {import('express').Handler} */ function requireUser(req, res, next) { ...

Receiving a blank array when sending a piece of information

Currently, I am working on building an API for podcasts using POSTMAN, mongoose, and nodejs. The API consists of Category Name and an Episodes array which includes Episode Number, Episode Name, Episode Description, and a title image. However, when posting ...

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

What is the best way to call the app.js function from an HTML page in an Express.js environment

Is there a way to trigger the function init() { // } located in app.js from an HTML page? <a href='javascript:init();'> Trigger init </a> The issue with the code above is that it searches for function init() only on the client side ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Solve the TypeScript path when using jest.mock

I am currently in the process of adding unit tests to a TypeScript project that utilizes compilerOptions.paths. My goal is to mock an import for testing purposes. However, I have encountered an issue where jest is unable to resolve the module to be mocked ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

When attempting to retrieve information from the API, an error occurred stating that property 'subscribe' is not found in type 'void'

I've attempted to use this code for fetching data from an API. Below is the content of my product.service.ts file: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, Observ ...

Retrieve only non-null objects using a Graphql query

I am attempting to execute a query similar to this: { people{ pet{ name } } } Here is the result I am getting: { "people": { "pet": null } }, { "people": { "pet": { name: "steve" } } } I am looking to only retrieve data fo ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...

Creating a new Express JS application

I've encountered an issue with my express application. When I run the server and navigate to localhost in my browser, the index page loads but without the image that should be displayed. The browser console shows a 404 error for the image URL. GET ht ...

Leveraging Environment Variables in Separate JavaScript Files within a Node Express Application

After trying various methods and searching extensively online, I am struggling to use environment variables in a separate JavaScript file within an Express App. My Setup: In my Express app, I have an index.js file that serves an HTML page with associated ...

What methods should I use to host my web application using Node/Express?

I have a question that may seem basic to some, but I'm completely lost when it comes to Node/Express. I have only worked with Apache servers (usually WAMP/XAMP for testing), so I have no clue how to serve my web app. My folder structure looks like th ...

A guide on using the patch API and Multer package to update files and images

After reviewing my code, I have successfully created a user model and imported it into the controller. Additionally, I have also imported an upload middleware from another directory where the code is written for uploading files/images using the multer pack ...

Remove items from a Mongo database utilizing Mongoose, Express, and Node.js

I'm currently working on setting up a basic backend todo list using mongoose, mongo, express and ejs. However, I've encountered an issue while trying to delete an item from MongoDB using mongoose by clicking on the html checkbox. The specific c ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

difficulty encountered when transmitting data via ajax to an express server

Just starting out with backend and ran into an issue when trying to send data using vanilla ajax to my express server. Can anyone spot where I might be making a mistake? Here is my ajax request: var xhttp = new XMLHttpRequest(); xhttp.onload ...

Express Node is capable of accessing cookies in a DELETE request, however it does not have the same capability in

My Node Express application has a request DELETE /refresh, which is able to read HTTP-only cookies. However, when I change it to a POST request, the application can no longer retrieve the token value and instead sees it as undefined. This issue only occur ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Using Jest and TypeScript to mock the return value of react-oidc-context

For our project, we utilize react-oidc-context to handle user authentication using oidc-client-ts under the hood. The useAuth function provided by react-oidc-context gives us access to important information such as isAuthenticated, isLoading, and the auth ...