Right now, when I handle a success / failure message, I handle both response types via the same listener and check the response type to decide whether it’s a success or failure response. Like this:
server
socket.on('event', function(){
//process request
if (success) {
var data = {
foo : 'useful',
bar : 'info'
}
} else {
var data = 'failure message';
}
socket.emit('eventResponse', data);
}
client
socket.on('eventResponse', function(){
if (typeof data = "object") {
//assume successful response / utilize response data
} else {
//assume failure and utilize data as failure message
}
}
At this point, I always send a failure as a string containing the failure message, and always send success as an object, containing response data. I think of this as sort of a dependency topic. Since I’m not defining clear input type dependencies, it may be considered bad practice, or perhaps because doing this is simpler and faster, it may be good. I’m not sure.
Is it a correct/acceptable practice to handle error / success responses in this way, or should I handle the two separately?
If you consistently do this, and document it, and it fulfills all your needs, then there is no problem with it.
But if you know you’ll need more complex error indicators in the future, or if you do this in some places but not others, or if your handlers are so complex that a combined function becomes unreadably large, then nip the practice in the bud now.