android - Exception handling on AsyncQueryHandler -
when using android's asyncqueryhandler
, there easy way handle exceptions thrown asynchronous insert or need write own version of class?
poking around asyncqueryhandler
source became clear extend suit needs without pain. since "asyncqueryhandler exception handling" doesn't give on google or i've attached source below in case else ever finds in same situation.
basically is, extends asyncqueryhandler
's internal worker thread , wraps call through thread's super.handlemessage
in try-catch block, sends caught exceptions main thread in message, gets passed onerror
callback. default onerror
re-throws exception.
/** * thin wrapper around @link {@link asyncqueryhandler} provides callback invoked * if asynchronous operation caused exception. */ public class sturdyasyncqueryhandler extends asyncqueryhandler { public sturdyasyncqueryhandler(contentresolver cr) { super(cr); } /** * thin wrapper around {@link asyncqueryhandler.workerhandler} catches <code>runtimeexception</code> * thrown , passes them in reply message. exception occurred * in <code>result</code> field. */ protected class sturdyworkerhandler extends asyncqueryhandler.workerhandler { public sturdyworkerhandler(looper looper) { super(looper); } @override public void handlemessage(message msg) { try { super.handlemessage(msg); } catch (runtimeexception x) { // pass exception calling thread (will in args.result) workerargs args = (workerargs) msg.obj; message reply = args.handler.obtainmessage(msg.what); args.result = x; reply.obj = args; reply.arg1 = msg.arg1; reply.sendtotarget(); } } } @override protected handler createhandler(looper looper) { return new sturdyworkerhandler(looper); } /** * called when runtime exception occurred during asynchronous operation. * <p> * default re-throws exception * @param token - token passed operation * @param cookie - cookie passed operation * @param error - <code>runtimeexception</code> thrown during * operation */ public void onerror(int token, object cookie, runtimeexception error) { throw error; } @override public void handlemessage(message msg) { if (msg.obj instanceof workerargs) { workerargs args = (workerargs) msg.obj; if (args.result instanceof runtimeexception) { onerror(msg.what, args.cookie, (runtimeexception) args.result); return; } } super.handlemessage(msg); } }
Comments
Post a Comment