Dealing with errors in Express.js using promises and the suncc middleware

Dealing with both sync errors and promise errors in the same code can be tricky. Below is an example of how I'm attempting to handle them, but I'm unsure if it's functioning correctly. Any suggestions are appreciated.

helpers.list({
            limit: 1
        })
        .then(function(results) {
          // Handle cases where there are no results
          if (results.length < 1) {
            return next();
          }
            res.render('post/post');
        })
         .fail(function(error){
           next(error);
        })

Answer №1

Avoid mixing sync errors with promises

I have come across a reliable solution which involves throwing a rejected promise so that the `fail()` function can catch it towards the end

helpers.list({
            limit: 1
        })
        .then(function(results) {
          // Take care of scenarios where there are no results
          if (results.length < 1) {
           // Call next to proceed to the next route, for example 404
           next();
            return Parse.Promise.reject('No results were found')
          }
            res.render('post/post');
        })
         .fail(function(error){

           // Use call next(error); to trigger the express error handler
        })

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

After performing more than 6 queries, Node.js becomes unresponsive and stops listening

I have been working with expressJs and encountered an issue with executing a query multiple times: router.post('/Index_api/Reminder/Delete',function(req, res) { Reminder_Id = req.body; DeleteRow('Reminders','Reminder ...

Discovering Request Parameters in Express Node.js

The hashtag key in the URL contains all the query strings. http://localhost:3002/callback#access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer How can we access the parameters after the hashtag? ...

Mongoose is not patient enough to wait for the document to be returned in the callback

In my Express.js project, I am making multiple database calls that are dependent on each other. I am using pg-promise for calls to the PostgreSQL database and Mongoose for calls to MongoDB. Everything is functioning correctly, but there are instances where ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

The Socket.io Chat application is indicating a memory leak with the EventEmitter, detecting 11 listeners that have been added. To resolve this issue

My private chat application is built using socket.io, node.js, and MySQL. However, I encountered an error when trying to use socket.on('example', function(data){...});. The error code thrown is related to a possible EventEmitter memory leak with ...

While local production and development prove effective, Heroku restricts calls to the Express server only

Update: Heroku is only recognizing my server file, struggling to incorporate the client as well. Attempting to deploy my first solo-built app on Heroku. While still a work in progress, the basic functionalities are operational. The current version works s ...

Capture - retrieve the data of the specified route using a specific keyword

Query I am managing multiple nested routers and I need to retrieve the entire string that corresponds to the request's path. To clarify, please refer to this code snippet: const express = require('express') const app = express() const rout ...

Using the POST method in Node.js is not functioning properly on the Replit server when using express

Recently diving into the world of backend development, I have been utilizing Node.js on a Replit server with express to host an application for handling files: However, hitting a roadblock when attempting to execute a post request! var express = ...

Uniting File Generation and sendFile in Node.js using Express

In the realm of Node.js, there exists a technique for generating new files. Here's an example: let writeStream = fs.createWriteStream(name); writeStream.write("f1,f2,f3"); writeStream.write("1,2,3"); writeStream.end(); Additionally, if we possess th ...

Obtain the current URL in a Node.js configuration file

In my application using the express framework, I have the following code in my app.js file: var express = require('express'); var app = module.exports = express(); var config = require('./config.js')(app, express); // Including ...

The Node.js application is up and running on the Node server, but unfortunately, no output is

Greetings, I am a beginner in nodejs. var io = require('socket.io').listen(server); users = []; connections = []; server.listen(process.env.PORT || 3000); console.log('server running....on Pro'); app.get ('/', function(re ...

The POST request in Node.js using Express is returning an undefined value

Having an issue with Node.js + express on the backend while trying to parse the body of a simple POST-request. The server console is showing "undefined" as the result. Tried various options from StackOverflow without success, even after including body-par ...

Node-webkit: The perfect solution for creating applications that seamlessly transition between web and desktop environments using a single code

Given the task at hand, I have been presented with the following considerations: Develop a desktop application using Nodeweb kit. Also develop a web application using the same code base. Both applications should have an identical appearance. Both apps mu ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

Test in Node.js with Mocha exceeds its time limit

My Promise-based code is timing out even after all my efforts to fix it. Can someone help me with this issue? export function listCurrentUserPermissions(req, res, next) { return UserPermission.findAll({ where: { ac ...

Searching for a string in an array using the $in operator in M

I have a custom model defined as follows: var MessageSchema = new Schema({ msgID: String, patientList: [String], created_at: Date, updated_at: Date }); The patientList is always dynamic in nature. I am attempting to construct a Mongoose ...

What is the best way to transfer an image from Firebase storage to the Facebook Marketing API?

Could someone assist me in understanding how to download an image from Node/Express/Cloud Functions for Firebase? Currently, I'm only able to retrieve an object containing information about my image in Firebase storage (using getMetadata();) let ima ...

No user was located using Mongoose.findOne()

Utilizing fetch() to make a call to a URL looks like this: const context = useContext(AuthContext); const navigate = useNavigate(); const handleSubmit = (event) => { event.preventDefault(); const dat ...

Using the Postman application, the Sequelize delete request with payload functions correctly; however, it encounters issues when executed through the Vue

Struggling to send PUT and DELETE requests via my express backend to a sqlite database. PUT request is working, but DELETE request consistently fails. Verified headers in the network tab, both are correct (application/json). Postman can successfully delet ...

How do I go about transferring data from an excel sheet to an external API with the help of JQuery/Node.js?

If I possess an excel document that needs to be delivered to an API endpoint which demands the following headers: Content-Type: multipart/form-data Content-Disposition: form-data; name="fileData"; filename="Form_SOMETHING(2).xlsx" Is it plausible for me ...