Jesper
Jesper

Reputation: 2094

UnhandledPromiseRejection in Express.js

I hope I'm supplying enough information for this question, but I can't understand why my callback function returns Unhandled Promise Rejection when I on purpose 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.

I'm calling the function here in routes:

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

        CreateSnippetResource(req, function(err) {

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

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

And 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'm trying to handle the error when title is not entered. I have a validator in my schema-module that looks like this:

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

And indeed the returned error-message from the callback CreateSnippetResource is The title is empty. So how come I get this Promise-error?

I'm assuming it has something to do with how I handle the snippet.save(), but can't see how it's not handled. Can you please help?

Upvotes: 0

Views: 365

Answers (2)

Jesper
Jesper

Reputation: 2094

As it turns out, I was an idiot, and forgot that I accidentally putted the whole function in the callback. The callback is then executed twice, and thus returns Error: Can't set headers after they are sent.

Upvotes: 1

Bergi
Bergi

Reputation: 665316

Why does my callback function return Unhandled Promise Rejection when I on purpose want to catch the error?

That will happen when your callback throws another exception. This will reject the promise returned by the .catch(…) call, and that rejection is nowhere handled.

Upvotes: 1

Related Questions