Node.js 是否可以使用morgan记录错误消息?

Node.js 是否可以使用morgan记录错误消息?,node.js,express,logging,morgan,Node.js,Express,Logging,Morgan,我使用morgan记录请求和响应,一切正常。我想知道是否有任何方法,我可以记录错误消息也?例如:如果应用程序中的try-catch块失败,我将向用户返回500错误和自定义消息。但是有没有一种方法可以记录实际的错误。消息 我的应用程序中的代码片段 try { // Resend OTP let otp_server_response = await sms.resendOTP(mobile_number, resend_mode); if(otp_server_r

我使用morgan记录请求和响应,一切正常。我想知道是否有任何方法,我可以记录错误消息也?例如:如果应用程序中的
try-catch
块失败,我将向用户返回
500
错误和自定义消息。但是有没有一种方法可以记录实际的
错误。消息

我的应用程序中的代码片段

 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" });
 }
 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
                        }
                    )
                }
            )
试试看{
//重发OTP
让otp_服务器_响应=等待sms.resendOTP(手机号码,重发模式);
如果(otp_服务器_响应.type==“成功”){
返回res.status(200).json({message:“OTP_RESENT”});
}否则{

console.log(otp_server_response.message);//我不这么认为。据我所知,此模块不包含实际错误。也就是说,您可以使用以下命令将错误保存在错误处理程序中

req.error = err;

然后您可以访问自定义令牌中的req.error。

它不应该是
res
而不是
req
?好吧,假设您不想将错误发送给客户端,我不这么认为……不,我不想将其发送给客户端。这是针对MVP生产案例。对于客户端,我正在发送如上所示的自定义消息。但不知怎的,在执行上述操作时,错误没有被记录。哦!好吧…我丢失了格式中的令牌。是的,它现在可以工作了。好吧,酷,我只是想说你应该能够访问morgan中间件中的req.error。没问题。很好。