如何实现req / res拦截器

时间:2016-10-11 11:24:17

标签: javascript node.js feathersjs

我尝试使用feathers-client实现请求/响应拦截器。

目的是将全局元数据添加到请求并删除响应正文。另外,我想使用响应拦截器来实现全局错误处理程序。

我查看了钩子,但是如果发生任何错误,似乎after* Hooks不会被执行。

feathersclient()
  ...
  .configure(function() {
      const app = this;
      app.mixins.push(function(service) {
        service.before(function(hook) {
          console.log('SENT', service.path, hook);
          return hook;
        });
        service.after(function(hook) {
          // Never fired if req produces an error
          console.log('RECEIVE', service.path, hook);
          return hook;
        });
      });
  })

2 个答案:

答案 0 :(得分:1)

你是对的,遗憾的是没有很好的办法可以解决发生的错误。然而,v1.6.0的羽毛钩将支持onError个处理程序。在此之前,您可以使用自己的错误处理程序创建服务mixin,如下所示:

feathersclient()
  ...
  .configure(function() {
    const app = this;
    app.mixins.push(function(service) {
      const mixin = {};

      app.methods.forEach(method => {
        if(typeof service[method] === 'function') {
          mixin[method] = function(... args) {
            return this._super(... args).catch(error => {
              // do some error handling here
              throw error;
            });
          }
        }
      });

      service.mixin(mixin);
    });
  })

答案 1 :(得分:0)

可悲的是,我只能通过monky-patching send-method来解决:

    app.mixins.push(function(service) {
      // monky patch send() to fetch errors
      const oldSend = service.send;
      service.send = function(...args) {
        return oldSend.apply(service, args)
          .catch(e => {
            console.log('ERR', e);
            throw e; // re-throw error
          });
      };
    });
相关问题