Before, call the 3rd party service, each method is almost "long" this way, write up verbose, change trouble, but also easy to change leaks.
public void Authorizeroletouser (Long userId, list<long> roleIds) {try { Power.authorizeroletouser (UserId, roleids); } catch (Motancustomexception ex) {if (Ex.getcode (). Equals (Msuserexception.notlogin (). GetCode ())) throw Userexception.notlogin (); if (Ex.getcode (). Equals (Mspowerexception.havenopower (). GetCode ())) throw Powerexception.havenopower (); Throw ex; } catch (Motanserviceexception ex) {Cathelper.logeventservice ("Power-authorizeroletouser", "Authorizeroletouser", Ex.getstatus (), Ex.geterrorcode (), Ex.getmessage ()); Throw ex; } catch (Motanabstractexception ex) {Cathelper.logeventservice ("Power-authorizeroletouser", "Authorizeroletouser", Ex.getstatus (), Ex.geterrorcode (), Ex.getmessage ()); Throw ex; } catch (Exception ex) {cathelper.logerror (ex); Throw ex; }}
I have learned and extracted the encapsulation, will try ... catch: Fetch is public, get these 2 methods.
Import java.util.function.supplier;public static <T> T tryCatch (supplier<t> Supplier, String serviceName, String methodName) {try {return supplier.get (); } catch (Motancustomexception ex) {if (Ex.getcode (). Equals (Msuserexception.notlogin (). GetCode ())) throw Userexception.notlogin (); if (Ex.getcode (). Equals (Mspowerexception.havenopower (). GetCode ())) throw Powerexception.havenopower (); Throw ex; } catch (Motanserviceexception ex) {Cathelper.logeventservice (ServiceName + "-" + MethodName, MethodName, EX.GETST ATUs (), Ex.geterrorcode (), Ex.getmessage ()); Throw ex; } catch (Motanabstractexception ex) {Cathelper.logeventservice (ServiceName + "-" + MethodName, MethodName, ex.gets Tatus (), Ex.geterrorcode (), Ex.getmessage ()); Throw ex; } catch (Exception ex) {cathelper.logerror (ex); Throw ex; }}public static void TryCatch (Runnable Runnable, String serviceName, String methodName) {TryCatch ((), {runnable.run (); return null; }, ServiceName, methodName);}
Now it's so simple to use. Like this non-return value:
public void Authorizeroletouser (Long userId, list<long> roleids) { TryCatch (), { Power.authorizeroletouser (UserId, roleids); }, "Power", "Authorizeroletouser");}
And this has the return value:
Public list<roledto> Listrolebyuser (Long userId) { return TryCatch ((), Power.listrolebyuser (userid), " Power "," Listrolebyuser ");}
This is my first Java article. In the process of learning Java, there are both surprises and disappointments. will continue to share the experience in the future.
Java: An example of simplifying code with lambda expressions