Just beginning my journey with Express and JS, eager to learn more about Next.js

I am currently learning and exploring new concepts, so please excuse any mistakes in my terminology or code :).

Here is the code snippet I have:

    try {
      if (!username || 
        !password || 
        !email || 
        !firstname || 
        !lastname || 
        !phone_number||
        !role) {
        next({
          name: "MissingCustomerDataError",
          message: "Required Field - username, password, email, firstname, lastname, phone_number"
        });
        // throw new RouteError({
        //     name: "MissingCustomerDataError",
        //     message: "Required Field - username, password, email, firstname, lastname, phone_number"
        //   });
      }
   ...(some more code)
      const cust = await createCustomer({ 
        username, 
        password, 
        email, 
        firstname, 
        lastname, 
        phone_number, 
        role, 
        address });

I expected that calling next(...) would exit this logic and trigger my error handler attached after this route. Unfortunately, it still calls the database function. Using throw does take me out of this logic and into the catch block. Shouldn't next also navigate out of this try block and move on? I believe there might be a conceptual misunderstanding on my end. Thanks for your help!

Answer №1

Your assumption is incorrect. Invoking the next function triggers the subsequent middleware/request handler, without halting the current operation. To exit a function promptly, you need to utilize a return statement like so:

if (!name || 
    !age || 
    !email || 
    !address) {
    return next({
      name: "MissingDataError",
      message: "Required Fields - name, age, email, address"
    });

Alternatively, errors can be managed through the use of a throw statement.

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

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

In React frontend, POST request is being sent with an empty body, whereas in Postman, the body is sent correctly

I am currently developing a web application using React for the frontend and Node Express for the backend. I've encountered an issue where when I send a POST request with a JSON body to one of my endpoints, the req.body object on the server side is em ...

Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option: window.onload = () => { let [...opt ...

How to retrieve a specific value using jQuery based on the name attribute

I'm having an issue retrieving the selected value from the menu and assigning it to the `country` variable. Whenever I try, I keep encountering the error: No parameterless constructor defined. The `UpdateClient` function is triggered by clicking on t ...

Mastering the art of incorporating live JavaScript search functionality that updates in real-time as the user continues typing on the same

Trying to implement a JavaScript search feature to find a div within the same page. The current code being used for the search query display is: $('.form-search').on('submit',function(){return false;}); $('.form-search .btn') ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

Testing reactive streams with marble diagrams and functions

Upon returning an object from the Observable, one of its properties is a function. Even after assigning an empty function and emitting the object, the expectation using toBeObservable fails due to a non-deep match. For testing purposes, I am utilizing r ...

AJAX messaging system utilizes setInterval to stack identifiers

Currently, I am working on a chat project at school that involves AJAX. The issue I am facing is when a user clicks on a link (representing the person they want to chat with), an onclick event triggers a function called load(id) where the id of the person ...

Locate the class within the entire page and eliminate a different div

I'm facing an issue where I need to remove the .box class when the .test div is added with the .active class. I've attempted to do this but it doesn't seem to be working. Can anyone provide some insight into what might be causing this proble ...

Is it possible to utilize the YouTube Data API without specifying a redirect_uri? If so, how would one go

After developing a NodeJS application for uploading videos to a YouTube channel via the command line interface, I encountered a challenge. Every upload redirects me to a specific redirect_uri as per Google Docs requirements. To bypass user authorization/s ...

Trouble transmitting JSON data from Java to local Node.js Express server

Currently, I am facing an issue with sending a JSON string to a local server. Below is the code snippet I am using to make the POST request: HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead try { HttpPost request = new ...

During the build process, the parameters in Next.js are not accessible

I am currently using Next.js 13 with the experimental app directory. My application utilizes dynamic routing in the following format: https://app.domain/[itemid]/[slug] Within my [slug] directory, if I create a server-side route file pages.jsx with th ...

Finding the precise top offset position with jQuery upon scrolling – a step-by-step guide

I need help with detecting the offset top of a TR element when it is clicked. It works fine initially, but once the page is scrolled, the offset().top value changes. How can I resolve this issue? $(function() { $('tr').click(function() { ...

An odd error is being thrown by the remove function of the Redux-form field array

Let's consider this scenario: I am working with an array of objects that I am displaying using Redux Form Field Array. Here is a sample structure: [{ index: 0, overlapRecord: '127.0.0.1' }, { index: 1, overlapRecord: ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object. Here is the JSON data I am working with: [ { "some_key1": [ {"key": "va ...

Ways to automatically shift focus as each input reaches its maximum character limit

Looking to enhance the user experience for a credit card form I am creating, I want the browser to automatically shift focus to the next input field once the user has entered the maximum number of characters allowed in the maxlength attribute of the input. ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Insert an item into a document within a MongoDB database

I am currently working on an app that features chatrooms, each with its own mongodb collection. One of my goals is to store the chat history for each chatroom in a "messages" field, along with other relevant information. Database: myApp Collection: "chatr ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...