Home > other >  Why is my code error not stopping the function in nodejs?
Why is my code error not stopping the function in nodejs?

Time:12-27

My self and another developer are working on an API using node.js and we are not advanced coders yet. We ran into problem. I will try and explain the problem here with sample references.

We have an API route that would be called on the frontend, please this is just a sample and not the real code. client said the codes should be private. We want to stop the function when an error is detected in another function we called. I am sure that we are not doing it rightly. Here is the API route for this post request and we called another function that we exported and imported here.

We simply want the httpCreateHarsh function to end if there is an error in the anotherFunction. With what we have, the error is seen in console.log when the user is not an admin for example but the httpCreateHarshfunction keeps running until it reaches the last line. Is this possible? Or is there another way we can structure the code to achieve this?

Shared sample of my code

const callAnotherFunction = require("../anotherfunction")
const httpCreateHarsh = async(req, res) => {
  await callAnotherFunction(req, res);
  return res.status(200).json('created')
}
//This is the second function we called:
const obj = {
  status: 'success',
  code: '244'
}
const anotherFunction = async(req, res) => {
  if (req.body.user !== 'admin') {
    return res.status(401).json('Unauthorized')
  }
  return obj
}
export default = anotherFunction
//The route here:
const express = require('express');
const router = express.Router();
const httpCreateHarsh = require('../httpCreateHarsh');
router.post("/harsh", httpCreateHarsh)

CodePudding user response:

You couldn't return the res object in your second function.

To solve this problem you could throw exceptions and catch them in your handler function.

// request handler function
const httpCreateHarsh = async (req, res) => {

    try {
        await callAnotherFunction(req, res);
    } catch (e) {
        return res.status(401).json('Unauthorized')
    }

    return res.status(200).json('created')

}

const anotherFunction = asyn(req, res) => {
    if (req.body.user !== 'admin') {
        throw new Error('Unauthorized')
    }
    return obj
}

CodePudding user response:

What you can do is you can wrap the code in httpCreateHarsh in an try...catch so whenever there is error inside it it will trigger the catch block and u exit the api.

const httpCreateHarsh = async(req, res)=>{
   try{
       await callAnotherFunction(req, res);

       return res.status(200).json('created')
   } catch(err){
         return res.status(401).json('Unauthorized')
   }
}

As an addition to this code you can return a promise from anotherFunction so that the catch block will be triggered once the promise is rejected.

For Exmaple:


const anotherFunction = async(req, res) => {
  return new Promise(function(myResolve, myReject) {
    if (req.body.user !== 'admin') {
    myReject();
  }

  myResolve(obj);
  });
 
}

  • Related