Reputation: 436
I have a question regarding SignalR on the clientside (JS). Is there a way to intercept incoming messages at the clientside? I am working on a chat application with a lot traffic on the socket. I want to be able to execute code (catch errors if any) on every incoming event.
Looking at the docs I can't find any existing solution for this. Is there one?
Upvotes: 1
Views: 1140
Reputation: 336
My first thought for a workaround was using a function to 'pipe' the callback functions through first.
E.G.
private pipeSignal(cb: (arg: any) => void): (arg: any) => void {
const errors = checkForErrors();
if(errors){
return () => {
// Handle error here
};
}
return cb;
}
I then thought setting up the handlers could look as follows:
this.hubConnection.on(
'MyMethod1',
this.pipeSignal((method1Val) => {
console.log(method1Val);
})
);
this.hubConnection.on(
'MyMethod2',
this.pipeSignal((method2Val) => {
console.log(method2Val);
})
);
BUT, this results in the 'pipeSignal' function being called only once when setting up the event listener. Thereafter, it will not be called.
I think the only option here would be to have a function that checks for errors in every event listener callback.
private hasErrors(arg: any): boolean {
const errors = checkForErrors();
if(errors){
// Handle error here
return true;
}
return false;
}
Then in each signal event callback you can try checking for errors like this:
this.hubConnection.on(
'MyMethod1',
(method1Val) => {
if(!this.hasErrors(method1Val)){
// Can continue knowing there are no errors
console.log(method1Val);
}
}
);
Turns out I was close with my 'pipeSignal' function. Rather than running the error logic in the pipeSignal function, I return a function that wraps the error logic and the callback:
private pipeSignal(cb: (arg: any) => void): (arg: any) => void {
return (arg) => {
const errors = checkForErrors();
if(errors){
// handle errors
} else {
// proceed with callback as there are no errors
cb(arg);
}
};
}
Now this can be used as I imagined before:
this.hubConnection.on(
'MyMethod1',
this.pipeSignal((method1Val) => {
console.log(method1Val);
})
);
Upvotes: 1