scala - How to call a method in a catch clause on an object defined in a try clause? -


i creating redis pubsub client in try-catch block. in try block, client initialised callback forward messages client. if there's problem sending message client, exception thrown, in case need stop redis client. here's code:

try {   val redisclient = redispubsub(     channels = seq(currentuserid.tostring),     patterns = seq(),     onmessage = (pubsubmessage: pubsubmessage) => {       responseobserver.onvalue(pubsubmessage.data)     }   ) } catch {   case e: runtimeexception =>     // redisclient isn't defined here...     redisclient.unsubscribe(currentuserid.tostring)     redisclient.stop()     messagestreamresult.complete(try(true))     responseobserver.oncompleted() } 

the problem redis client val isn't defined in catch block because there may have been exception creating it. can't move try-catch block callback because there's no way (that can find) of referring redisclient object within callback (this doesn't resolve).

to solve i'm instantiating redisclient var outside try-catch block. inside try block stop client , assign new redispubsub (created above) redisclient var. that's ugly hack error prone (e.g. if there genuinely is problem creating second client, catch block try call methods on erroneous object).

is there better way of writing code can correctly call stop() on redisclient if exception raised when trying send message responseobserver?

update

i've solved using promises. there simpler way though?

that exception handler not going invoked if there problem sending message. problems in setting client. so answer talks handling errors when sending messages.

as callback referring client, think want register callback after creating client rather trying pass callback in when create it. here sample code debashish ghosh this.

presumably callback going run in thread, if uses redisclient you'll have careful concurrency. ideally callback client object through argument. if not, perhaps using volatile easiest way deal that, although suspect you'd trouble if multiple callbacks can fail @ once. perhaps use actor manage client connection, debashish has done?


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -