Psi Psi - 1 month ago 7
Node.js Question

How to implement req/res interceptors

I try to implement Request/Response interceptors using feathers-client.

The purpose is to add global meta-data to the request and strip the response body. Additional I want to use the response interceptor to implement a global error handler.

I looked at the hooks but it seems the

after*
Hooks wont be executed if any error happens.

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;
});
});
})

Answer

You are correct, unfortunately there is not a great way to hook into errors that happen. v1.6.0 of feathers-hooks will support onError handlers however. Until then you could create a service mixin with your own error handler like this:

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);
    });
  })