如何实现 req/res 拦截器
How to implement req/res interceptors
我尝试使用 feathers-client 实现 Request/Response 拦截器。
目的是向请求添加全局元数据并剥离响应主体。另外我想使用响应拦截器来实现全局错误处理程序。
我查看了钩子,但似乎 after*
如果发生任何错误,钩子将不会被执行。
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;
});
});
})
可悲的是,我只能通过修改发送方法来解决它:
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
});
};
});
你是对的,不幸的是没有一个很好的方法来挂钩发生的错误。但是,feathers-hooks v1.6.0 将支持 onError
处理程序。在那之前,您可以像这样使用自己的错误处理程序创建服务混合:
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);
});
})
我尝试使用 feathers-client 实现 Request/Response 拦截器。
目的是向请求添加全局元数据并剥离响应主体。另外我想使用响应拦截器来实现全局错误处理程序。
我查看了钩子,但似乎 after*
如果发生任何错误,钩子将不会被执行。
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;
});
});
})
可悲的是,我只能通过修改发送方法来解决它:
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
});
};
});
你是对的,不幸的是没有一个很好的方法来挂钩发生的错误。但是,feathers-hooks v1.6.0 将支持 onError
处理程序。在那之前,您可以像这样使用自己的错误处理程序创建服务混合:
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);
});
})