Add proxy method to check for exception
518057
private void addProxyCheckException(TypeSpec.Builder classBuilder) {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("checkException")
                .addModifiers(Modifier.PRIVATE)
                .returns(Throwable.class)
                .addParameter(ClassName.get("android.os", "Parcel"), "reply")
                .addStatement("int code = reply.readInt()")
                .addStatement("Throwable exception = null")
                .beginControlFlow("if (code != 0)")
                .addStatement("String msg = reply.readString()")
                .beginControlFlow("if (code == REMOTER_EXCEPTION_CODE)")
                .addStatement("exception = (Throwable) reply.readSerializable()")
                .endControlFlow()
                .beginControlFlow("else")
                .addStatement("exception = new RuntimeException(msg)")
                .endControlFlow()
                .endControlFlow()
                .addStatement("return exception");
        classBuilder.addMethod(methodBuilder.build());
    }
351613
@Override
  @SuppressWarnings("unchecked") // safe since the proxy implements type
  public T getFake(Class<?> type) {
    return (T) Proxy.newProxyInstance(FakeMessagesProvider.class.getClassLoader(), new Class<?>[] {type},
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            if (method.getName().equals("ensureInjected")) {
              return true;
            } else if (method.getName().equals("hashCode")) {
              return proxy.getClass().hashCode();
            } else if (method.getName().equals("equals")) {
              return proxy.getClass().equals(args[0].getClass());
            } else if (method.getReturnType() == String.class) {
              return buildMessage(method, args);
            } else if (method.getReturnType() == SafeHtml.class) {
              return SafeHtmlUtils.fromTrustedString(buildMessage(method, args));
            } else {
              throw new IllegalArgumentException(method.getName()
                  + " must return either String or SafeHtml");
            }
          }
        });
  }
655713
public static <T> T buildProxy(String proxyType, Class<T> clazz, Invoker proxyInvoker) throws Exception {
        try {
            ExtensionClass<Proxy> ext = ExtensionLoaderFactory.getExtensionLoader(Proxy.class)
                .getExtensionClass(proxyType);
            if (ext == null) {
                throw ExceptionUtils.buildRuntime("consumer.proxy", proxyType,
                    "Unsupported proxy of client!");
            }
            Proxy proxy = ext.getExtInstance();
            return proxy.getProxy(clazz, proxyInvoker);
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new SofaRpcRuntimeException(e.getMessage(), e);
        }
    }
1153671
def _maybe_wrap_exception(exception):
    """"""
    if isinstance(exception, grpc.RpcError):
        return exceptions.from_grpc_error(exception)
    return exception
894095
def add_error(name=None, code=None, status=None):
    """"""
    if not name or not status or not code:
        raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
    myexception = type(name, (PyMacaronException, ), {"code": code, "status": status})
    globals()[name] = myexception
    if code in code_to_class:
        raise Exception("ERROR! Exception %s is already defined." % code)
    code_to_class[code] = myexception
    return myexception
1037398
private void startProxy() throws Exception {
    mProxyProcess = ProxyProcess.Factory.create();
    Runnable runProxy = () -> {
      try {
        mProxyProcess.start();
      } catch (InterruptedException e) {
        // this is expected
      } catch (Exception e) {
        // Log the exception as the RuntimeException will be caught and handled silently by JUnit
        LOG.error("Start proxy error", e);
        throw new RuntimeException(e + " \n Start Proxy Error \n" + e.getMessage(), e);
      }
    };

    mProxyThread = new Thread(runProxy);
    mProxyThread.setName("ProxyThread-" + System.identityHashCode(mProxyThread));
    mProxyThread.start();
    TestUtils.waitForReady(mProxyProcess);
  }
857872
def catch_exception(exception, message=None):
    
    def decorator(f):
        @click.pass_context
        def new_func(ctx, *args, **kwargs):
            try:
                return ctx.invoke(f, *args, **kwargs)
            except exception as e:
                message1 = message if message is not None else '{}'.format(e)
                click.echo(message1)
                ctx.exit(code=exit_codes.OTHER_FAILURE)
        return update_wrapper(new_func, f)
    return decorator
228431
function proxyObjErrors (proxyObj) {
  if (!proxyObj) { return '`proxyObj` not defined'; }

  let errors   = '';
  let expected = ['req', 'req', 'reqOpts', 'options'];

  _.each(expected, function (expect, index) {
    if (!proxyObj[expect]) {
      errors += (index ? ', ' : '') + 'Missing property: `' + expect + '`';
    }
  });

  return errors ? 'Errors found in `proxyObj`: [' + errors + ']' : false;
}
1162395
def catch_exceptions(*exceptions):
    """"""
    def wrap(fn):
        @functools.wraps(fn)
        def wrapped_f(*args, **kwargs):
            try:
                return fn(*args, **kwargs)
            except exceptions:
                t, value, traceback = sys.exc_info()
                # If any resource does not exist, return None instead of raising
                if str(value.status) == '404':
                    return None
                e = CloudApiException(str(value), value.reason, value.status)
                raise_(CloudApiException, e, traceback)
        return wrapped_f
    return wrap
773883
def method_missing(*args, &block)
      # Get the configuration
      if args.last.is_a?(Hash)
        options = args.last
      else
        args << options = {}
      end
      
      # Get any existing condition that may need to be merged
      if_condition = options.delete(:if)
      unless_condition = options.delete(:unless)
      
      # Provide scope access to configuration in case the block is evaluated
      # within the object instance
      proxy = self
      proxy_condition = @condition
      
      # Replace the configuration condition with the one configured for this
      # proxy, merging together any existing conditions
      options[:if] = lambda do |*condition_args|
        # Block may be executed within the context of the actual object, so
        # it'll either be the first argument or the executing context
        object = condition_args.first || self
        
        proxy.evaluate_method(object, proxy_condition) &&
        Array(if_condition).all? {|condition| proxy.evaluate_method(object, condition)} &&
        !Array(unless_condition).any? {|condition| proxy.evaluate_method(object, condition)}
      end
      
      # Evaluate the method on the owner class with the condition proxied
      # through
      machine.owner_class.send(*args, &block)
    end
209385
public static <T> T getTargetObject(Object proxy, Class<T> clazz) throws Exception {
        while( (AopUtils.isJdkDynamicProxy(proxy))) {
            return clazz.cast(getTargetObject(((Advised)proxy).getTargetSource().getTarget(), clazz));
        }

        return clazz.cast(proxy);
    }
251635
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
        throws Throwable {

        if (method.getName().equals("toString") && args.length == 0) {
            return locator.toString();
        }

        if (Object.class.equals(method.getDeclaringClass())) {
            return proxy.invokeSuper(obj, args);
        }

        if (WrapsDriver.class.isAssignableFrom(method.getDeclaringClass()) && method.getName()
            .equals("getWrappedDriver")) {
            return driver;
        }

        WebElement realElement = locator.findElement();
        return getObject(realElement, method, args);
    }
138506
private static ReflectionException handleException(String methodName, InvocationTargetException e) {
        LOGGER.error("Couldn't invoke method " + methodName, e);
        return new ReflectionException(e);
    }
43011
def execute(self, proxy, method, args):
        """"""
        try:
            result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args))
        except xmlrpc.ERRORS as exc:
            self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc))
            self.return_code = error.EX_NOINPUT if "not find" in getattr(exc, "faultString", "") else error.EX_DATAERR
        else:
            if not self.options.quiet:
                if self.options.repr:
                    # Pretty-print if requested, or it's a collection and not a scalar
                    result = pformat(result)
                elif hasattr(result, "__iter__"):
                    result = '\n'.join(i if isinstance(i, basestring) else pformat(i) for i in result)
                print(fmt.to_console(result))
628359
def capture_exception(fn):
    """"""
    def wrapped(*args):
        try:
            return fn(*args)
        except Exception as e:
            return e
    return wrapped
1214557
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
    {
        String methodName = method.getName();
        Class[] params = method.getParameterTypes();

        // equals and hashCode are special cased
        if (methodName.equals("equals") &&
            params.length == 1 && params[0].equals(Object.class)) {
            Object value = args[0];
            if (value == null || !Proxy.isProxyClass(value.getClass()))
                return new Boolean(false);

            BurlapProxy handler = (BurlapProxy) Proxy.getInvocationHandler(value);

            return new Boolean(_url.equals(handler.getURL()));
        }
        else if (methodName.equals("hashCode") && params.length == 0)
            return new Integer(_url.hashCode());
        else if (methodName.equals("getBurlapType"))
            return proxy.getClass().getInterfaces()[0].getName();
        else if (methodName.equals("getBurlapURL"))
            return _url.toString();
        else if (methodName.equals("toString") && params.length == 0)
            return getClass().getSimpleName() + "[" + _url + "]";

        InputStream is = null;

        URLConnection conn = null;
        HttpURLConnection httpConn = null;
        try {
            conn = _factory.openConnection(_url);

            httpConn = (HttpURLConnection) conn;

            httpConn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml");

            OutputStream os;

            try {
                os = conn.getOutputStream();
            } catch (Exception e) {
                throw new BurlapRuntimeException(e);
            }

            BurlapOutput out = _factory.getBurlapOutput(os);

            if (!_factory.isOverloadEnabled()) {
            }
            else if (args != null)
                methodName = methodName + "__" + args.length;
            else
                methodName = methodName + "__0";

            if (log.isLoggable(Level.FINE))
                log.fine(this + " calling " + methodName + " (" + method + ")");

            out.call(methodName, args);

            try {
                os.flush();
            } catch (Exception e) {
                throw new BurlapRuntimeException(e);
            }

            if (conn instanceof HttpURLConnection) {
                httpConn = (HttpURLConnection) conn;
                int code = 500;

                try {
                    code = httpConn.getResponseCode();
                } catch (Exception e) {
                }

                if (code != 200) {
                    StringBuffer sb = new StringBuffer();
                    int ch;

                    try {
                        is = httpConn.getInputStream();

                        if (is != null) {
                            while ((ch = is.read()) >= 0)
                                sb.append((char) ch);

                            is.close();
                        }

                        is = httpConn.getErrorStream();
                        if (is != null) {
                            while ((ch = is.read()) >= 0)
                                sb.append((char) ch);
                        }
                    } catch (FileNotFoundException e) {
                        throw new BurlapRuntimeException(code + ": " + String.valueOf(e));
                    } catch (IOException e) {
                    }

                    if (is != null)
                        is.close();

                    throw new BurlapProtocolException(code + ": " + sb.toString());
                }
            }

            is = conn.getInputStream();

            AbstractBurlapInput in = _factory.getBurlapInput(is);

            return in.readReply(method.getReturnType());
        } catch (BurlapProtocolException e) {
            throw new BurlapRuntimeException(e);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }

            if (httpConn != null)
                httpConn.disconnect();
        }
    }
505901
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
    {
        String mangleName;

        synchronized (_mangleMap) {
            mangleName = _mangleMap.get(method);
        }

        if (mangleName == null) {
            String methodName = method.getName();
            Class<?>[] params = method.getParameterTypes();

            // equals and hashCode are special cased
            if (methodName.equals("equals")
                && params.length == 1 && params[0].equals(Object.class)) {
                Object value = args[0];
                if (value == null || !Proxy.isProxyClass(value.getClass()))
                    return Boolean.FALSE;

                Object proxyHandler = Proxy.getInvocationHandler(value);

                if (!(proxyHandler instanceof HessianProxy))
                    return Boolean.FALSE;

                HessianProxy handler = (HessianProxy) proxyHandler;

                return new Boolean(_url.equals(handler.getURL()));
            }
            else if (methodName.equals("hashCode") && params.length == 0)
                return new Integer(_url.hashCode());
            else if (methodName.equals("getHessianType"))
                return proxy.getClass().getInterfaces()[0].getName();
            else if (methodName.equals("getHessianURL"))
                return _url.toString();
            else if (methodName.equals("toString") && params.length == 0)
                return "HessianProxy[" + _url + "]";

            if (!_factory.isOverloadEnabled())
                mangleName = method.getName();
            else
                mangleName = mangleName(method);

            synchronized (_mangleMap) {
                _mangleMap.put(method, mangleName);
            }
        }

        InputStream is = null;
        HessianConnection conn = null;

        try {
            if (log.isLoggable(Level.FINER))
                log.finer("Hessian[" + _url + "] calling " + mangleName);

            conn = sendRequest(mangleName, args);

            is = getInputStream(conn);

            if (log.isLoggable(Level.FINEST)) {
                PrintWriter dbg = new PrintWriter(new LogWriter(log));
                HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

                dIs.startTop2();

                is = dIs;
            }

            AbstractHessianInput in;

            int code = is.read();

            if (code == 'H') {
                int major = is.read();
                int minor = is.read();

                in = _factory.getHessian2Input(is);

                Object value = in.readReply(method.getReturnType());

                return value;
            }
            else if (code == 'r') {
                int major = is.read();
                int minor = is.read();

                in = _factory.getHessianInput(is);

                in.startReplyBody();

                Object value = in.readObject(method.getReturnType());

                if (value instanceof InputStream) {
                    value = new ResultInputStream(conn, is, in, (InputStream) value);
                    is = null;
                    conn = null;
                }
                else
                    in.completeReply();

                return value;
            }
            else
                throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
        } catch (HessianProtocolException e) {
            throw new HessianRuntimeException(e);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (Exception e) {
                log.log(Level.FINE, e.toString(), e);
            }

            try {
                if (conn != null)
                    conn.destroy();
            } catch (Exception e) {
                log.log(Level.FINE, e.toString(), e);
            }
        }
    }