如何在 Express.js 中将 Celebrate 验证错误记录到控制台?
我有一个 Express.js 应用程序,在其中尝试记录 Celebrate 返回的验证错误控制台,以便我可以使用我使用的日志服务(即 GCP 的 Cloud Logging)来分析它们。
我目前只是按照文档中的建议使用 Celebrate 提供的错误处理中间件:
// app.js
const { errors } = require('celebrate');
...
app.use(errors());
...
如何扩展中间件(无需重新实现它),以便它也将验证错误记录到控制台?
I have an Express.js app in which I'm trying to log the validation errors returned by Celebrate to the console so that I can analyze them with the logging service that I use (which is GCP's Cloud Logging).
I'm currently just using the error handling middleware provided by Celebrate as suggested in the documentation:
// app.js
const { errors } = require('celebrate');
...
app.use(errors());
...
How can I extend the middleware (without re-implementing it) so that it also logs the validation errors to the console?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的最简单方法似乎是在 Celebrate 错误中间件之前定义另一个错误中间件,该中间件检查错误是否是 Celebrate 错误(使用 isCelebrateError 方法)并如果是这样,它将其记录到控制台:
在 Celebrate 的
errors()
中间件之前包含日志记录中间件非常重要,因为errors()
返回 JSON 响应并且没有其他中间件追赶(您可以查看庆祝源代码 的实施细节errors()
)。The simplest way to achieve this seems to be by defining another error middleware before the Celebrate error middleware, that checks whether the error is a Celebrate error (using the
isCelebrateError
method) and if so it logs it to the console:It is important to include the logging middleware before Celebrate's
errors()
middleware sinceerrors()
returns a JSON response and no other middleware is run after it (you can check out the Celebrate source code for the implementation details oferrors()
).