1

I need to send a error message, and the full error object from nodejs backend to frontend.

I issue a error not declaring "ret" variable.

In my frontend I receive:

{"success":false,"message":"ret is not defined","results":{}}

As we can see, the results is empty. How could I receive the full "err" object into "results"?

//error log-backend

ReferenceError: ret is not defined
    at router.get (C:\nodeapp\cloudnh_v2\server\routes\config_geral.js:24:8)
    at <anonymous>

//router

'use strict';
    router.get('/',async (req,res,next)=>{  
        try {
           const connection = await pool.getConnection();
           try {
              ret={success:true}
              return res.send(ret);
            } finally {
                pool.releaseConnection(connection);
            }
        } catch (err) {
            return  res.status(500).send({ success:false,message: err.message, results:err}); // 500
      }
    });
Luiz Alves
  • 2,575
  • 4
  • 34
  • 75
  • i guess you need to throw err first to catch it later or you can use promises – Hemant Rajpoot Nov 08 '17 at 11:36
  • Possible duplicate of [How to print a stack trace in Node.js?](https://stackoverflow.com/questions/2923858/how-to-print-a-stack-trace-in-node-js) – str Nov 08 '17 at 11:36
  • @TGrif Yes, I know. I am simulating an error and I´d like to see that error on frontend. – Luiz Alves Nov 08 '17 at 11:40
  • @str I don´t think my question is a duplicate. My problem is send the error object to frontend not print the stack on backend. – Luiz Alves Nov 08 '17 at 11:41
  • @LuizAlves You already seem to know how to send information from the backend to the frontend (you are sending `err.message`, for example). So your question isn't really about the sending part but about the accessing part. The linked question answers exactly that (`err.stack`). – str Nov 08 '17 at 11:45
  • @str Ok, thank you. (err.stack) solved my problem. Thank you very much – Luiz Alves Nov 08 '17 at 11:49

1 Answers1

-1

Try this one

'use strict';
router.get('/',async (req,res,next)=>{  
    try {
       const connection = await pool.getConnection();
       try {
          ret={success:true}
          return res.send(ret);
        } finally {
            pool.releaseConnection(connection);
        }
    } catch (err) {
        return  res.status(500).json({ success:false,message: err.message, results:JSON.stringify(err)}); // 500
  }
});
Afraz Ahmad
  • 386
  • 1
  • 5
  • 20