Issue with UnhandledPromiseRejectionWarning in Mongoose/Typescript even with catch block

I'm facing an issue with an UnhandledPromiseRejectionWarning in my code. The specific scenario involves a Mongoose Index named 'id', where I am testing the insertion of a duplicate ID that should be handled appropriately.

router.post('/create/:id', jsonParser, (req: Request, res: Response) => {
    let { id } = req.params;
    if (!req.body) {
        return res.sendStatus(400)
    }

    // @TODO add validation on JSON
    let promise = Requirement.create({id: id, data: req.body.data, deleted: false});

    promise.then((requirement) => {
        return res.json(requirement);
    });

    promise.catch((reason) => {
        let err = {'error': reason};
        return res.json(err);
    });
});

The response JSON confirms that my rejection handler is being executed:

{
    "error": {
        "name": "MongoError",
        "message": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }",
        "driver": true,
        "index": 0,
        "code": 11000,
        "errmsg": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }"
    }
}

The warnings I am encountering are as follows:

(node:11408) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : "REQ001" }
(node:11408) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Answer №1

It seems like you're on the right track

var a = promise.then(…);
var b = promise.catch(…);

by creating a branch in the chain. When promise is rejected, the catch callback will handle it and fulfill promise b, however, promise a gets rejected as well without any handling.

To address this issue, consider utilizing both arguments of the then method like so:

Requirement.create({id: id, data: req.body.data, deleted: false})
.then(requirement => {
    res.json(requirement);
}, reason => {
    let err = {'error': reason};
    res.json(err);
});

Answer №2

catch is used to capture errors thrown by promise, but does not catch errors from promise.then(...). If an error occurs within then, it will result in an unhandled rejection. Even if the error is not explicitly thrown, but is propagated from promise, it will still be considered uncaught within this promise.

A better approach would be:

promise
.then((requirement) => {
    return res.json(requirement);
})
.catch((reason) => {
    let err = {'error': reason};
    return res.json(err);
});

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

Sending data with an Http POST request in Angular 2

I'm having difficulty with a POST request that I am trying to make: sendRequest() { var body = 'username=myusername&password=mypassword'; var headers = new Headers(); headers.append('Content-Type', 'applicat ...

Move divs that are currently not visible on the screen to a new position using CSS animations

Upon entering the site, I would like certain divs to animate from an offscreen position. I came across this code snippet: $( document ).ready(function() { $('.box-wrapper').each(function(index, element) { setTimeout(function(){ ...

Tips on adding up polygon values in mapbox

After providing detailed information about my issue, I was criticized for seeking help, so I will be more general in my explanation. I am trying to calculate the sum of values for each location within a polygon drawn on Mapbox. I have the code to insert th ...

Enhance the functionality of jQuery sortable by including additional details

I have a li list that I have implemented sortable functionality using jQuery. In order to ensure that the updated data is sent to the correct destination, I need to include some hidden values in the serialized data. How can I achieve this? HTML <ul i ...

The function ensure_csrf_token is failing to set the CSRF cookie in the cookies section

I am facing an issue with setting up a CSRF token in my application. Firstly, I have a simple generic view in Python: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

I'm struggling to make sense of this syntax, could someone kindly clarify for me?

const players = [ { name: "alice", team: "yellow", points: 15, inventory: ["gloves", "hat", "socks"] }, { name: "david", team: "pur ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

Selecting a value from a populated dropdown and checking the corresponding checkbox in SQL Server

There are 8 checkboxes in this example: <table style="border-collapse: collapse; width: 100%;" border="1"> <tbody> <tr style="height: 21px;"> <td style="width: 25%; height: 21px;"><strong>Technology</strong& ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...

Adding different colors for a range of values in the Grey_CircularLinearGauge component of DOJO can be achieved by customizing the

I'm currently working with the dojo toolkit and I am looking to incorporate the Grey_CircularLinearGauge component into my project. Here is an example of how I want it to look: In addition, I also need to customize the colors based on specific value ...

The type undefined cannot be assigned to the type even with a null check

When looking at my code, I encounter an error stating Argument of type 'Definition | undefined' is not assignable to parameter of type 'Definition'. Even though I am checking if the object value is not undefined with if (defs[type] != u ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Encountered an error while using vue-tiny-slider: Uncaught TypeError in promise - t2 is not recognized as a function

I'm currently using Vue 3 and have installed the vue-tiny-slider library from https://github.com/viktorlarsson/vue-tiny-slider. However, I encountered an error stating 't2 is not a function'. Since the documentation doesn't provide inst ...

Resizing tables dynamically using HTML and JavaScript

I am attempting to reproduce the functionality demonstrated in this example When dealing with a large table, I want it to resize to display 10 entries and paginate them accordingly. The only thing I require is the pagination feature without the search bar ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

The function useNavigate in React Router DOM is failing to correctly redirect the page

When a user tries to register, the code below is supposed to redirect them from the registration screen to the login screen. Despite successfully registering in the database, submitting the form still results in an error message "Registration failed!" with ...