Cannot stop nodejs function

56 Views Asked by At

I have a nodejs serverless backend which takes an interger and then execute some code. My problem is that if I send a string, I still get a 200 code response with null data.

To stop the function and send an error message I'm trying to check if the request is an interger with if and else statements but its not working. So, is it possible to do it like this, or is there a better way to stop the execution and send an error?

app.post('/xrp', (req, res) => {
  axios.get('https://www.surbtc.com/api/v2/markets/btc-clp/ticker')
    .then(response => {
      var clpbtc = parseFloat(response.data.ticker.min_ask[0]);
      if (typeof clpbtc === 'number') {
        coinTicker('bittrex', 'XRP_BTC')
        .then(response => {
          var xrpbtc = response.rawData.Bid;
          var exchangeRate = clpbtc * xrpbtc;
          if (xrpbtc) {
            var cantidadCLP = req.body.numero;
            var cantidadXRP = parseFloat(req.body.numero) / exchangeRate;
            var fee = 0.025;
            var oppositeFee = 0.975
            var totalCompraXRP = cantidadXRP * oppositeFee;
            res.status(200).json({ "cantidadCLP" : cantidadCLP, "cantidadXRP" : cantidadXRP, "fee": fee, "oppositeFee": oppositeFee, "totalCompraXRP": totalCompraXRP})
          } else {
            res.sendStatus(500).send("No válido2")
          }
        })
        .catch(error => {
            res.sendStatus(500).json(error);
        })
      } else {
        res.sendStatus(500).send("No válido")
      }
    })
    .catch(error => {
        res.sendStatus(500).json(error);
    });
  });
1

There are 1 best solutions below

2
On

Your problem is that you're parsing the parameter as a float anyway so even if you send a string, it will convert to a number and your query will simply return no data, hence the null response.

parseFloat('This is a string')
// => NaN

typeof parseFloat('This is a string')
// => 'number'

This is a weird property of javascript, where typeof NaN == 'number'

To accommodate for this, change your code to the following:

.then(response => {
      var clpbtc = parseFloat(response.data.ticker.min_ask[0]);
      if (!isNaN(clpbtc)) {
        coinTicker('bittrex', 'XRP_BTC')

Now, if you pass in a string, you should get a 500 response.