delegates - How to wrap every WCF call in a try-catch block -
delegates - How to wrap every WCF call in a try-catch block -
i have website need create asynchronous calls wcf service. want wrap each phone call in try-catch block can deal timeoutexceptions , communicationexceptions.
however, don't want copy-paste exact same try-catch block every time create phone call service. there way can utilize delegates write try-catch block once? still want capture exception messages.
i want phone call like:
// method returns void trycatchhelper(x => x.wcfmethod1(param1, param2)); // method has homecoming value no params var returnvalue = trycatchhelper(x => x.wcfmethod2());
edit: here's code looks now:
user getuser(int id) { user returnuser = null; seek { // open wcf channel, etc. returnuser = mywcfclient.getuser(id); } grab (timeoutexception exception) { log(exception.message); // abort wcf mill } grab (communicationexception exception) { log(exception.message); // abort wcf mill } homecoming returnuser; }
i don't want utilize same try-catch block in every single method set in repository. tried doing this, gave me error on params. know i'm not using them correctly, need way define delegate can stand in of wcf method calls want make:
delegate object wcfaction(params object[] parameters); object dowcfaction(wcfaction action, params object[] parameters) { object returnvalue = null; seek { // open wcf channel, etc. returnvalue = action(parameters); } grab (timeoutexception exception) { log(exception.message); // abort wcf mill } grab (communicationexception exception) { log(exception.message); // abort wcf mill } homecoming returnvalue; } void mainmethod() { // compiler error user user = dowcfaction(getuser, 1); }
you set class this. sorry there 2 exception handlers here, not one:
class logger { // handle wcf calls homecoming void static public void execwithlog(action action) { seek { action(); } catch(exception e) { log(e); throw; } } // handle wcf calls homecoming value static public t execwithlog<t>(func<t> action) { t result = default(t); seek { result = action(); } grab (exception e) { log(e); throw; } homecoming result; } static void log(exception e) { system.diagnostics.debug.writeline(e.tostring()); } }
then, phone call methods:
static void main(string[] args) { logger.execwithlog(() => dosomethingreturnvoid()); logger.execwithlog(() => dosomethingreturnvoidparamint(5)); int = logger.execwithlog<int>(() => dosomethingreturnint()); string b = logger.execwithlog<string>(() => dosomethingreturnstringparamint(5)); }
wcf delegates try-catch
Comments
Post a Comment