5

I am logging request and responses using morgan and everything is working fine. I would like to know if there is any way in which I could log the error messages too? For ex: if a try catch block fails in my application, I am returning a 500 error and a custom message back to the user. But is there a way in which I could log the actual error.message?

Snippet from my app

 try {
     // Resend OTP
     let otp_server_response = await sms.resendOTP(mobile_number, resend_mode);

     if(otp_server_response.type === "success") {
         return res.status(200).json({ message: "OTP_RESENT" });
     } else {
         console.log(otp_server_response.message); // <= Log this message in morgan logs if request reaches here
         return res.status(400).json({ message: "OTP_RESENDING_FAILED" });
     }
 }
 catch (error) {
     console.log(error.message); // <= Log this message in morgan logs if request reaches here
     return res.status(500).json({ message: "SOME_ERROR_OCCURRED" });
 }

Snippet of my logger file

 const errorLogFormat    = ":requestId :status :res[content-length] :response-time ms";
 .
 .
 .
 // Log error responses (4xx and 5xx)
            morganLogger(
                errorLogFormat,
                {
                    skip: (req, res) => {
                        return res.statusCode < 400
                    },
                    stream: rfs(
                        "responses.log",
                        {
                            interval: "1d",
                            path: logDirectory
                        }
                    )
                }
            )
Ayan
  • 2,738
  • 3
  • 35
  • 76

1 Answers1

8

Don't think so. From my knowledge, this module doesn't contain actual errors. That being said, You could just save the error in your error handler with something like

req.error = err;

and then you can access req.error in your custom token.

silencedogood
  • 3,209
  • 1
  • 11
  • 36
  • 1
    shouldn't it be `res` rather than `req`? – Ayan Oct 24 '19 at 15:21
  • 1
    Well, assuming you're not looking to send the error to the client, I don't think so... – silencedogood Oct 24 '19 at 15:27
  • Nope, I aint looking to send it to the client. Its for a MVP production case. For clients, I am sending the custom messages as shown above. But somehow on doing the above, the error isnt logged. – Ayan Oct 24 '19 at 15:28
  • Oh! ok...I was missing the token in the format. Yep it works now. – Ayan Oct 24 '19 at 15:32
  • Okay cool, I was just about to say you should be able to access req.error in your morgan middleware no prob. Good deal. – silencedogood Oct 24 '19 at 15:32