-1
  • after I hit the below api call I am getting errors. (node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. (node:5548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    • so I put try catch inside my then method but still I am not able to catch the errors inside my catch.
    • I debugged by putting console console.log("try catch error--->", error), but still no help
    • can you let me know whether I have added try and catch properly inside my then method.
    • providing my code snippet below
   axios.get(AppConstants.GET_JWT_TOKEN_URL, {
        auth: {
            username: credentials.auth.racfId, password: credentials.auth.password
        }
    })
        .then((jwtResponse) => {
            console.log("jwt then----->", jwtResponse.data.jwt);
            var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
            //   var jwtToken = `Bearer ewefewehjefwwe wehwefwefwef uih uihu`;
            console.log('then formatUrl --->', formatUrl);

            axios.get(formatUrl, {
                headers: {
                    "Authorization": jwtToken, "Content-Type": 'application/json'

                }
            })

                .then((response) => {
                    try {
                        console.log("sports suceess then0--->");
                        const file = Buffer.from(response.data.content, 'base64');
                        const fileType = mime.contentType(response.data.contentInfo.fileType);
                        const fileExtension = response.data.contentInfo.fileType.toLowerCase();
                        const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
                        console.log("sports suceess fileName--->", fileName);
                        ResponseUtil.callService(res, url);

                        res.send({});
                    }
                    catch (error) {
                        console.log("try catch error--->", error)
                        const errorMessage = error.response.data.message;


                    }

                })


                .catch((e) => {
                    console.log("e catch sports0--->", e);
                    console.log("e.message catch sports0--->", e.message);

                    console.log("catch sports--->", e.response);

                    if (e.response) {
                        return res.status(e.response.status).send(e.response.data);
                    }
                    res.status(500).send(e.message || 'Something wrong');
                });



        });

logs

sports suceess then0--->

sports suceess fileName---> ioreioreio=erierioerioerio
  callService ===>  /erpoperoperop/rejklerklkler
  else if responseutil.jsURL ===>  http://players/erpoperoperop/rejklerklkler
  URL ===>  http://players/erpoperoperop/rejklerklkler
express deprecated res.send(status, body): Use res.status(status).send(body) instead server\services\utils\ResponseUtil.js:56:30
(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:5548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  • Can you rephrase the question? It's hard to understanding what you are asking. – shaochuancs Jun 11 '19 at 01:14
  • @shaochuancs hey sorry did see the question before I posted...I am trying to implement try catch isnide axios then method :( –  Jun 11 '19 at 01:21

1 Answers1

0

There are a couple of issues with this implementation. The first issue is that you've neglected to return your promises so that they are applied to the promise chain. If you do not return the promise, then errors will not propagate up the promise chain, which defeats the purpose of promises. The second issue is that you're attempting to send a response twice, once in ResponseUtil.callService(res, url) and another time directly after that (e.g. res.send({});).

The console errors point out both of these mistakes:

1) Failure to chain the promises

(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.

2) Duplicate call to res.send

express deprecated res.send(status, body): Use res.status(status).send(body) instead server\services\utils\ResponseUtil.js:56:30


I'm going to make the assumption that ResponseUtil.callService(res, url) returns a promise to answer this question since it appears that is the case.

axios.get(AppConstants.GET_JWT_TOKEN_URL, {
    auth: {
        username: credentials.auth.racfId,
        password: credentials.auth.password
    }
}).then((jwtResponse) => {
    // Return the promise from get so it is applied to the promise chain
    return axios.get(formatUrl, {
        headers: {
            "Authorization": `Bearer ${jwtResponse.data.jwt}`,
            "Content-Type": 'application/json'

        }
    }).then((response) => {
        const file = Buffer.from(response.data.content, 'base64');
        const fileType = mime.contentType(response.data.contentInfo.fileType);
        const fileExtension = response.data.contentInfo.fileType.toLowerCase();
        const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
        // Return the promise from call service so it is applied to the promise chain
        return ResponseUtil.callService(res, url);
    });
}).catch((e) => {
    // Catch any error that occurred in the promise chain...
    if (e.response) {
        return res.status(e.response.status).send(e.response.data);
    }
    return res.status(500).send(e.message || 'Something wrong');
});
Jake Holzinger
  • 5,783
  • 2
  • 19
  • 33
  • thanks that error went away...I updated my question. Can you tell me how to remove negative marks :( –  Jun 11 '19 at 13:40
  • If you remove this line `res.send({});` how to send the data to the browser? since in browser I need to download the pdf –  Jun 11 '19 at 14:21
  • `ResponseUtil` is sending the response. The error message says do not use `res.send(status, body)` and it is coming from `ResponseUtil`. Unfortunately you cannot remove the negative marks given by other users, they likely gave you negative marks because your post was badly formatted initially. To avoid it in the future make sure your question is correctly formatted before posting it. You can of course delete your question, this would remove the negative marks from your account. – Jake Holzinger Jun 11 '19 at 16:51
  • but gave good explanation this will help others...is it anyway can I remove the negative mark without deleting :( –  Jun 11 '19 at 17:59
  • You can try improving the formatting of your question further so it is more readable. It may not be clear to everyone what you are asking, if you improve the question other users may come along and give it an upvote. Generally a good way to ask a question is to include information about the problem you are trying to solve. Your question presumes that using `try/catch` is the solution to your problem, which is what we like to call an [XY problem](http://xyproblem.info/). – Jake Holzinger Jun 11 '19 at 18:25
  • hey can you help me with this question using mock data https://stackoverflow.com/questions/56385656/react-app-local-storage-is-not-setting-up/56467574#56467574 –  Jun 11 '19 at 18:27