Is there a way to prompt Express to acknowledge a mistake encountered during my Teradata database query?

My current setup involves using Express to connect to my Teradata database, and everything works perfectly when there are no errors.

However, when an error occurs during a Teradata call, I can see the output in my console window but I'm unsure how to set up an error handler.

Although this seems like a basic issue, I am new to Express and would greatly appreciate any assistance.

Here is the code for the Express call:

router.post('/sp_run', function (req, res) {
    var sql = "CALL DB.STORED_PROC1(1,P_ERROR_CODE,P_MSG);";
    console.log(sql);
  return teradata.read(sql)
      .then((x) => {
        console.log(x);
   res.send(x);
      });
  });

This is the error information displayed in my console:

CALL DB.STORED_PROC1(1,P_ERROR_CODE,P_MSG);
express_1  | 2019-6-27 21:07:10 - error: [Teradata] Unable to execute query: CALL DB.STORED_PROC1(1,P_ERROR_CODE,P_MSG);
express_1  | Unhandled rejection Error: Error running instance method
express_1  | java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.10] [Error 7627] [SQLState HY000] STORED_PROC1:SELECT-INTO returned more than one row.

In case of an error, I want to send an email notification and provide a response to the frontend promptly instead of waiting indefinitely.

Answer №1

To avoid sending promises from this point, simply respond with a status variable of type boolean. Then, apply a condition on the frontend.

 router.post('/sp_run', function (req, res) {
     var sql = "CALL DB.STORED_PROC1(1,P_ERROR_CODE,P_MSG);";
     console.log(sql);

     return teradata.read(sql)
       .then((x) => {
          return res.json({
                   status: true,
                  message: 'All work fine',
                  result: x
              })
        }).catch(error => {
         //send email about failure
          return res.json({
                 status: false,
                 message: 'Failed',
                 error: error.message
           })
       });
    });

Alternatively, you can send a response with a status code and handle it using try/catch.

On the front end:

const getData = () => {
    // Here axios is used to call an API, you can use fetch or anything else.
    axios.post('/sp_run', {}).then(data => {
        if(!data.status) {
            alert(data.error)
        } else {
        // Work with the data
        }
    })

}

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

What is the best way to turn off ajax functionality when detecting IE8?

Encountering a significant problem where every time the save/cancel button is clicked, IE8 freezes (while Firefox and Chrome work without issue). When JavaScript is disabled in the browser, it works correctly. There is a suspicion that an ajax call linke ...

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

Expanding a div's size with CSS to fill the remaining space

Here's the setup I'm working with: <div class="parent"> <div class="moverBoy"></div> <div class="smartBoy"></div> </div> The parent element is fixed at 100x20 indefinitely. moverBoy and smartBoy are al ...

Customize the default SQL generation in EF 6 according to the entity type

Exploring the concept of entity classes public class MyTable { public Guid Id {get;set;} public string Name {get;set;} } When using EF, the generated code looks something like this: CreateTable( "dbo.MyTable", c => new ...

Issue with Google Maps API fetching data is resolved

const express = require('express'); const app = express(); const { Client } = require('@googlemaps/google-maps-services-js'); const googleMapsClient = new Client({apiKey:"myGoogleApiKey"}); app.use(express.json()); app.ge ...

What is the recommended value for the auto-incremented ID field when using the POST method in Node.js?

Currently, I am utilizing the mysql package for NodeJs in order to Post Data to a MySqlDB. Below is an example of my code: app.post('/countries', (req, res) => { const country = req.body.country; const city = req.body.city; const t ...

Implementing a feature in React where the active class is applied only to the next element upon clicking

I'm just starting out with React and working on a custom menu bar project. The Mobile menu includes 2 dropdown submenus, which I want to toggle open and close by clicking an arrow. Currently, the arrows are functioning, but when I click on one arrow, ...

Implementing a color filter on a camera using Three.js

Can a parameter be adjusted for the camera or renderer to apply a tint to everything on the stage, such as a red shade resembling a "glasses effect", without having to manually modify each object's materials? ...

Stop Element-UI from automatically applying the list-item style to li elements

I have a list of data elements that I am rendering in the following way: <ul> <li v-for="el in elements"> {{el.data}} </li> </ul> Here's how I style it in my .css file: ul { list-style-type: none; padd ...

Inconsistencies with Handlebars adding forward slashes "/" to page addresses are causing confusion among users

In my project, I have 10 unique .handlebars files that are being called using express GET methods as shown below: app.get('/pagename1', function(req, res, next) { res.render('page1'); }); app.get('/pagename2', function(req ...

Can dependency injection be implemented while utilizing the new operator?

My goal is to incorporate a strategy pattern into my program. Specifically, I want to be able to determine at runtime which class to create an instance of. Implementing this may seem straightforward at first: if(...) { this.service = new ServiceA(); } el ...

Retrieving data from a <div> element within an HTML string using jQuery and AJAX

Having trouble extracting a value from a div within an HTML string. Seeking assistance in identifying the issue. I've attempted various methods to retrieve the data, but none seem to work for me. It appears I may be overlooking something crucial. $( ...

Unpredictable term pulled from the Javascript/Ajax content

Can someone help me figure out how to randomly select just one word from a block of text using JavaScript? Here's the code I've been working with: function someFunction() { // need help here var word; $.ajax({ async: false, typ ...

Implement the insertion of JSON items in real-time by leveraging the power of Angular JS and

I'm facing a challenge trying to insert JSON items into a dynamic list: The structure of my JSON file is as follows: [ { "id":"34", "City":"New York", "Country":"USA" }, { "id":"22", "City":"Las vegas", "Country":"USA" }, { "id":"44", "City":"Paris" ...

Encountering an isObject issue while using the @material/core package

When attempting to run the project, I encountered this error in the console: isobject error Upon inspecting the package-lock.json file, I discovered that the isobject dependency was missing in @material-ui/core. Adding it manually resolved the issue. pac ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

Obtain JSON information from a Javascript response using Puppeteer:

While developing a test with Puppeteer and Node, I encountered the need to extract an access token from a response after logging in. Here is the current code snippet: //Click Login Button const loginButton = await page.$(".click-button.dark.ng-star-i ...

Tips for generating numerous queries within one GET request

Can I use node-pg to execute multiple queries in a single GET request? For instance, if I have code that looks like this: const getSomeInfo = (request, response) => { pool.query('SELECT * FROM jobs', (error, results) => { ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Mastering NodeJS Promises: Efficiently Handling Multiple http.get Requests

I have recently started learning about NodeJS and Promise functionality, so please be patient with me if this question seems uninformed. My goal is to first retrieve a database of records and then verify that the links associated with these records return ...