Dealing with Unhandled Promise Rejections in Express.js

I'm providing all the necessary details for this question, however I am confused as to why my callback function is returning an Unhandled Promise Rejection even though I deliberately want to catch the error:

(node:3144) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:3144) 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.

The function is being called in routes like this:

router.route("/home/create")
    .post(Authorization, function(req, res) {

        CreateSnippetResource(req, function(err) {

            if (err) {
                console.log(err.message)
            }

            res.redirect("/home")
        });
    });

This is the "CreateSnippetResource" function:

(function() {

    let User = require("../../Models/User");
    let Snippet = require("../../Models/Snippet");

    /**
     * Create a new snippet and save it to database
     * @param request
     * @param callback
     */
    module.exports = function(request, callback) {

        callback(
            User.findOne({ user: request.session.Auth.username }, function(err, user) {
                if (err || user === null) {
                    callback("User not found")
                }

                var snippet = new Snippet({
                    title: request.body.snippetName.split(".").shift(),
                    fileName: "." + request.body.snippetName.split(".").pop(),
                    postedBy: user._id,
                    snippet: [{
                        text: " "
                    }]
                });

                snippet.save().then().catch(function(err) {

                    callback(err)
                });
            }))
    };
}());

I have implemented a validator in my schema-module to handle errors when title is not entered. The validator looks like this:

SnippetSchema.path("title").validate(function(title) {
    return title.length > 0;
}, "The title is empty");

Even though the returned error message from the callback CreateSnippetResource is The title is empty, I am still encountering this Promise error. It seems related to how I handle the snippet.save(), but I can't figure out where the issue lies. Can someone provide assistance?

Answer №1

What is the reason behind my callback function returning an error of "Unhandled Promise Rejection" even though I am intentionally trying to handle the error?

This issue occurs when your callback throws an additional exception. As a result, the promise that is returned by the .catch(…) method gets rejected, and this rejection goes unhandled.

Answer №2

It seems that I made a silly mistake by inadvertently placing the entire function inside the callback. This caused the callback to be executed twice, resulting in the error message: "Can't set headers after they are sent."

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

Python sends back a list containing garbled characters to Ajax

Need help fixing the output of a Python list returned to Ajax, as it appears strange. ap.py @app.route('/_get_comUpdate/', methods=['POST']) def _get_comUpdate(): comNr = request.form.get('comNr') com_result ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Using jQuery to highlight the navigation menu when a specific div scrolls into view

I have implemented a side navigation consisting of circular divs. Clicking on one scrolls you to the corresponding .block div, and everything functions correctly. However, I am now curious if it is feasible to highlight the relevant .nav-item div based on ...

A guide on implementing the intl-tel-input plugin within an Angular 2+ project

Component : ng2-tel-input, Framework : Angular 4, JavaScript library : intl-tel-input Upon completing the installation with npm i ng2-tel-input I stumbled upon a note in the node_modules\intl-tel-input\src\js\intlTelInput.js file that ...

Why does Node.js sometimes give me a MySQL error: ECONNREFUSED?

Despite reviewing numerous similar inquiries like node.js mysql error: ECONNREFUSED, none of the proposed solutions have resolved my issue. When I executed mysql -hlocalhost -P 3306 -p*** from the command line, it successfully connected to my database. The ...

Sharing data between two PHP pages via an AJAX request

On my webpage, specifically on page 1.php, I am saving a variable to an input field text. Name:abc Done. After clicking the 'done' button, the name abc is sent to another page called 2.php via an Ajax request. In 2.php, I am storing the value ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

Is there a problem with AngularJS $state.go() not emitting $stateChangeSuccess?

In my scenario, I have controllers A and B located in different states. When I trigger $state.go('state_b');, Angular switches to state state_b and loads controller B. However, what surprises me is that I do not receive $stateChangeSuccess in my ...

The back button functionality in Android cannot be altered or overridden using JavaScript

Hey everyone, I'm currently in the process of developing a mobile application using phonegap. I'm facing an issue where I want to disable the functionality of the back button from navigating to the previous page. I simply want it to do nothing or ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...

Exploring the potentials of VivagraphJS alongside WebGL and the magic of event listeners

After coming across Vivagraph JS on GitHub, I was absolutely enthralled. However, I've encountered an issue that seems to be related to WebGL. My current objective is to: var graph = Viva.Graph.graph(); var layout = Viva.Graph.Layout.forceDirec ...

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

Managing errors in Google OAuth authentication with Node.js utilizing the passport and passport-google-oauth20 packages

Currently, I am developing an authentication Nodejs API using passport and passport-google-oauth20. Everything seems to be working fine, but I am facing an issue where I need to verify the user's email based on a specific domain. In my system, only e ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

Transform a log file into a JSON structure

In my log file titled request.log, the following entries are present: [2022-06-30T09:56:40.146Z] ### POST https://test.csdf/auth/send_otp { "method": "POST", "headers": { "User-Agent": "testing&q ...

In JS/JSON, a new line of data is generated every hour

Recently, I have been experimenting with DiscordJS and exploring its logging functionality. I am aware that the method I am using is outdated and may not be the most secure for actively changing data, but I am intrigued. let count = JSON.parse(fs.readFile ...

What techniques does Express or Connect use to create paths for routing?

When I want to create a new route in Express, I use the following command: app.get('/users', handler); This adds a new route object in app.routes.get: { path: '/admin/users', method: 'get', callbacks: [ [Function] ], ...