示例#1
0
        ///<summary>
        ///Sends a single message synchronously, blocking until the send is complete. Does not wait for
        ///a response.
        ///<c>
        ///NOTE: the underlying transport may be non-blocking, in which case the blocking is simulated
        ///by waits instead of using blocking network operations.
        ///</c>
        ///</summary>
        ///<exception cref="Thrift.TException">
        ///if a network or protocol error occurs while serializing or sending the request
        ///</exception>
        public static void SendSynchronousOneWayMessage(this IRequestChannel channel, IByteBuffer request)
        {
            TException exceptionHolder = null;

            request.Retain();
            using (ManualResetEventSlim latch = new ManualResetEventSlim(false))
            {
                channel.SendAsynchronousRequest(request, true, new RequestListener(
                                                    onRequestSent: reqs =>
                {
                    reqs?.Release();
                    latch.Set();
                },
                                                    //onResponseReceive: response =>
                                                    //{
                                                    //    communicatingComplete?.Invoke();
                                                    //    latch.Set();
                                                    //},
                                                    onChannelError: e =>
                {
                    exceptionHolder = e;
                    latch.Set();
                }));


                if (!latch.Wait(TimeSpan.FromMinutes(10)))
                {
                    throw new TException("wait for one-way request sent timeout.");
                }
            }
            if (exceptionHolder != null)
            {
                throw exceptionHolder;
            }
        }
示例#2
0
            public override void OnError(Exception error)
            {
                TException e = error as TException;

                if (e != null)
                {
                    IObservable <T> next;
                    try
                    {
                        if (parent.errorHandler == Stubs.CatchIgnore <T> )
                        {
                            next = Observable.Empty <T>(); // for avoid iOS AOT
                        }
                        else
                        {
                            next = parent.errorHandler(e);
                        }
                    }
                    catch (Exception ex)
                    {
                        try { observer.OnError(ex); } finally { Dispose(); };
                        return;
                    }

                    exceptionSubscription.Disposable = next.Subscribe(observer);
                }
                else
                {
                    try { observer.OnError(error); } finally { Dispose(); };
                    return;
                }
            }
示例#3
0
            /// <summary>
            /// Takes a TNumber and returns its absolute value.
            /// </summary>
            /// <param name="interpreter">The interpreter that the method is being called from.</param>
            /// <param name="value">The TNumber to get the absolute value of.</param>
            /// <returns>
            /// The TType resulting from the operation. An MExcpetion or null is returned when there is an error.
            /// </returns>
            public static TType Modulus(Interpreter interpreter, TType value)
            {
                TNumber    number;
                TException exception = AssignNumberValue(interpreter, out number, value);

                if (exception != null)
                {
                    return(exception);
                }

                // No errors yet, but make sure it's not a string
                if (number == null)
                {
                    return(new TException(interpreter, "Strings cannot be used in modulus operations"));
                }

                switch (number.TypeName)
                {
                case TType.T_INTEGER_TYPENAME:
                    return(new TInteger(System.Math.Abs(number.TIntegerValue)));

                case TType.T_REAL_TYPENAME:
                    return(new TReal(System.Math.Abs(number.TRealValue)));

                case TType.T_FRACTION_TYPENAME:
                    TFraction fraction = number as TFraction;
                    return(new TFraction(System.Math.Abs(fraction.Numerator), fraction.Denominator));
                    // No need to abs denominator as TFraction denominators are automatically kept positive
                }

                return(null);
            }
示例#4
0
        /// <summary>
        /// Throw an exception of the given type when called.
        /// </summary>
        public TException Throw <TException>() where TException : Exception, new()
        {
            var exception = new TException();

            Do(ci =>
            {
                throw exception;
            });
            return(exception);
        }
示例#5
0
 private void TryHandler(TException exception)
 {
     try
     {
         var result = this.handler(exception);
         result.Subscribe(new HandlerObserver(this));
     }
     catch (Exception e)
     {
         base.OnError(e);
     }
 }
示例#6
0
 private void FireChannelErrorCallback(IListener listener, TException exception)
 {
     try
     {
         listener.OnChannelError(exception);
     }
     catch (Exception t)
     {
         _logger.LogWarning(default(EventId), t, "Channel error listener callback triggered an exception");
         t.ThrowIfNecessary();
     }
 }
        /// <summary>
        /// Throw exception of the given type when
        /// the method is called
        /// </summary>
        /// <typeparam name="TException"></typeparam>
        /// <returns>Fluid Interface</returns>
        IMethodOptions IMethodOptions.Throws <TException>()
        {
            if (ThrowsException)
            {
                throw new InvalidOperationException(
                          "Can set only a single exception to throw on the same method call.");
            }

            ThrowsException  = true;
            ExceptionToThrow = new TException();
            return(this);
        }
示例#8
0
                public bool Handle(Exception exception)
                {
                    bool       handled = false;
                    TException e       = exception as TException;

                    if (e != null)
                    {
                        handled = this.handler(this.state, e);
                    }

                    return(handled);
                }
示例#9
0
        public static void HandleTException(Context ctx, TException ex)
        {
            var errMsg = AppCommon.Inst.ErrorTranslator.GetErrMessage(ex);

            if (errMsg != null)
            {
                Utils.Alert(ctx, errMsg.Item1, errMsg.Item2, false);
            }
            else
            {
                AppCommon.Inst.Log.Error(ex.ToString());
            }
        }
示例#10
0
            /// <summary>
            /// Compares one TNumber with another based on a given inequality operator.
            /// </summary>
            /// <param name="interpreter">The interpreter that the method is being called from.</param>
            /// <param name="a">The left hand operand of the comparison.</param>
            /// <param name="b">The right hand operand of the comparison.</param>
            /// <param name="inequality">The inequality operator to use in the comparison.</param>
            /// <returns>
            /// An TBoolean containing the result of the comparison. Returns a TException when there is an error.
            /// </returns>
            public static TType Inequality(Interpreter interpreter, TType a, TType b, string inequality)
            {
                // Try to get TNumber values from the TType arguments
                TNumber    numberA, numberB;
                TException exception = AssignNumberValue(interpreter, out numberA, a);

                if (exception != null)
                {
                    return(exception);
                }
                exception = AssignNumberValue(interpreter, out numberB, b);
                if (exception != null)
                {
                    return(exception);
                }

                // No errors, but one or both of the arguments could be a TString; check them
                if ((numberA == null) || (numberB == null))
                {
                    return(new TException(interpreter, "Strings cannot be used in inequality comparisons"));
                }

                bool result;

                switch (inequality)
                {
                case ">":
                    result = numberA.TRealValue > numberB.TRealValue;
                    break;

                case ">=":
                    result = numberA.TRealValue >= numberB.TRealValue;
                    break;

                case "<":
                    result = numberA.TRealValue < numberB.TRealValue;
                    break;

                case "<=":
                    result = numberA.TRealValue <= numberB.TRealValue;
                    break;

                default:
                    return(new TException(interpreter, "Invalid inequality operator given"));
                }

                return(new TBoolean(result));
            }
示例#11
0
        private void TestException <TException>()
            where TException : Exception, new()
        {
            Assert.IsNotNull(Activator.CreateInstance(typeof(TException), new object[] { "message" }));
            Assert.IsNotNull(Activator.CreateInstance(typeof(TException), new object[] { "message", new Exception("inner") }));

            var ex = new TException();

            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, ex);
                stream.Seek(0, SeekOrigin.Begin);
                formatter.Deserialize(stream);
            }
        }
示例#12
0
            public override void OnError(Exception error)
            {
                TException ex = error as TException;

                if (ex != null)
                {
                    IObservable <T> observable;
                    try
                    {
                        Delegate errorHandler = this.parent.errorHandler;
                        if (CatchObservable <T, TException> .Catch.< > f__mg$cache0 == null)
                        {
                            CatchObservable <T, TException> .Catch.< > f__mg$cache0 = new Func <TException, IObservable <T> >(Stubs.CatchIgnore <T>);
                        }
                        if (errorHandler == CatchObservable <T, TException> .Catch.< > f__mg$cache0)
                        {
                            observable = Observable.Empty <T>();
                        }
                        else
                        {
                            observable = this.parent.errorHandler(ex);
                        }
                    }
                    catch (Exception error2)
                    {
                        try
                        {
                            this.observer.OnError(error2);
                        }
                        finally
                        {
                            base.Dispose();
                        }
                        return;
                    }
                    this.exceptionSubscription.Disposable = observable.Subscribe(this.observer);
                    return;
                }
                try
                {
                    this.observer.OnError(error);
                }
                finally
                {
                    base.Dispose();
                }
            }
示例#13
0
 public static Func <T, string, TException> Combine <T, TException>(params Func <T, string, TException>[] guards)
     where TException : ArgumentException
 {
     return((paramValue, paramName) =>
     {
         TException ex = null;
         foreach (var guard in guards)
         {
             ex = guard(paramValue, paramName);
             if (ex != null)
             {
                 break;
             }
         }
         return ex;
     });
 }
示例#14
0
            /// <summary>
            /// Takes two TNumbers and returns the first one to the power of the other.
            /// </summary>
            /// <param name="interpreter">The interpreter that the method is being called from.</param>
            /// <param name="a">The left hand operand of the operation.</param>
            /// <param name="b">The right hand operand of the operation.</param>
            /// <returns>
            /// The TType resulting from the operation. An MExcpetion or null is returned when there is an error.
            /// </returns>
            public static TType Pow(Interpreter interpreter, TType a, TType b)
            {
                // Try to get TNumber values from the TType arguments
                TNumber    numberA, numberB;
                TException exception = AssignNumberValue(interpreter, out numberA, a);

                if (exception != null)
                {
                    return(exception);
                }
                exception = AssignNumberValue(interpreter, out numberB, b);
                if (exception != null)
                {
                    return(exception);
                }

                // No errors, but one or both of the arguments could be a TString; check them
                if ((numberA == null) || (numberB == null))
                {
                    return(new TException(interpreter, "Strings cannot be used in exponentiation operations"));
                }

                switch (numberA.TypeName)
                {
                case TType.T_INTEGER_TYPENAME:
                    return(new TInteger(
                               (long)System.Math.Round(System.Math.Pow(numberA.TRealValue, numberB.TRealValue))));

                case TType.T_REAL_TYPENAME:
                    return(new TReal(System.Math.Pow(numberA.TRealValue, numberB.TRealValue)));

                case TType.T_FRACTION_TYPENAME:
                    TFraction fraction  = numberA as TFraction;
                    long      numerator =
                        (long)System.Math.Round(System.Math.Pow(fraction.Numerator, numberB.TRealValue));
                    long denominator =
                        (long)System.Math.Round(System.Math.Pow(fraction.Denominator, numberB.TRealValue));
                    return(new TFraction(numerator, denominator));
                }

                return(null);
            }
示例#15
0
        public override Tuple <string, string> GetErrMessage(TException ex)
        {
            var se = ex as ServerError;

            if (se == null)
            {
                return(Tuple.Create("No Internet Connectivity", "Please ensure Wifi/data network is enabled and reachable"));
            }
            switch (se.Err)
            {
            case ErrorCode.InvalidArg:
                return(Tuple.Create("Invalid Input", "Please check and enter valid entries"));

            case ErrorCode.UserNotFound:
                return(Tuple.Create("Please Register", "User not registered. Please sign up."));

            default:
                return(null);
            }
        }
示例#16
0
        /// <summary>
        /// 设置仅重试哪些类型的异常。
        /// 允许多次调用(以OR方式处理)。
        /// </summary>
        /// <typeparam name="TException"></typeparam>
        /// <returns></returns>
        public Retry Filter <TException>() where TException : Exception
        {
            if (_filterList == null)
            {
                _filterList = new List <Func <Exception, bool> >();
            }


            _filterList.Add(
                (Exception ex) => {
                TException tex = ex as TException;
                if (tex == null)
                {
                    return(false);
                }

                return(true);
            });

            return(this);
        }
示例#17
0
            public override void OnError(Exception error)
            {
                TException val = error as TException;

                if (val != null)
                {
                    UniRx.IObservable <T> observable;
                    try
                    {
                        observable = ((!(parent.errorHandler == new Func <TException, UniRx.IObservable <T> >(Stubs.CatchIgnore <T>))) ? parent.errorHandler(val) : Observable.Empty <T>());
                    }
                    catch (Exception error2)
                    {
                        try
                        {
                            observer.OnError(error2);
                        }
                        finally
                        {
                            Dispose();
                        }
                        return;
                    }
                    SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable();
                    serialDisposable.Disposable           = singleAssignmentDisposable;
                    singleAssignmentDisposable.Disposable = observable.Subscribe(observer);
                }
                else
                {
                    try
                    {
                        observer.OnError(error);
                    }
                    finally
                    {
                        Dispose();
                    }
                }
            }
示例#18
0
        protected void OnError(Exception t)
        {
            _invoked = int.MinValue;
            TException wrappedException = WrapException(t);

            if (_channelError == null)
            {
                _channelError = wrappedException;
            }

            CancelAllTimeouts();

            List <Request> requests = new List <Request>();
            var            all      = this.GetAllRequests();

            requests.AddRange(all);
            _readerWriterLock.EnterWriteLock();
            try
            {
                _requestMap.Clear();
            }
            finally
            {
                _readerWriterLock.ExitWriteLock();
            }
            foreach (Request request in requests)
            {
                FireChannelErrorCallback(request.Listener, wrappedException);
            }

            IChannel channel = this.NettyChannel;

            if (channel.Open)
            {
                channel.CloseAsync();
            }
        }
示例#19
0
        ///<summary>
        ///Sends a single message synchronously, and blocks until the responses is received.
        ///</summary>
        ///<remarks>
        ///NOTE: the underlying transport may be non-blocking, in which case the blocking is simulated
        ///by waits instead of using blocking network operations.
        ///</remarks>
        ///<returns>The response, stored in a <see cref="IByteBuffer"/></returns>
        ///<exception cref="Thrift.TException">
        /// if an error occurs while serializing or sending the request or while receiving or de-serializing the response
        /// </exception>
        public static IByteBuffer SendSynchronousTwoWayMessage(this IRequestChannel channel, IByteBuffer request)
        {
            request?.Retain();
            IByteBuffer responseHolder  = null;
            TException  exceptionHolder = null;

            using (ManualResetEventSlim latch = new ManualResetEventSlim(false))
            {
                channel.SendAsynchronousRequest(request, false, new RequestListener(
                                                    onRequestSent: reqs => {
                    reqs?.Release();
                },
                                                    onResponseReceive: response =>
                {
                    responseHolder = response;
                    latch.Set();
                },
                                                    onChannelError: e =>
                {
                    exceptionHolder = e;
                    latch.Set();
                }
                                                    ));

                if (!latch.Wait(TimeSpan.FromMinutes(10)))
                {
                    throw new TException("wait for response/error timeout.");
                }
            }

            if (exceptionHolder != null)
            {
                throw exceptionHolder;
            }

            return(responseHolder);
        }
        public static void TestSerializationCtor <TException>()
            where TException : Exception, new()
        {
            var original = new TException();
            var msg      = "Some Message";

            typeof(Exception).GetField("_message",
                                       BindingFlags.NonPublic | BindingFlags.Instance)
            .SetValue(original, msg);

            using (var ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();

                formatter.Serialize(ms, original);

                ms.Seek(0, SeekOrigin.Begin);

                var deserialized = (TException)formatter.Deserialize(ms);

                deserialized.Message.Should().Be(msg);
                deserialized.ShouldBeEquivalentTo(original);
            }
        }
示例#21
0
 public abstract Tuple <string, string> GetErrMessage(TException ex);
 public void OnChannelError(TException requestException)
 {
     _excecption = requestException;
 }
 /// <summary>
 /// Throw exception of the given type when the property is called
 /// </summary>
 /// <typeparam name="TException"></typeparam>
 /// <returns>Fluid Interface</returns>
 IPropertyOptions <T> IPropertyOptions <T> .Throws <TException>()
 {
     ThrowsException  = true;
     ExceptionToThrow = new TException();
     return(this);
 }
示例#24
0
 public void OnChannelError(TException var1)
 {
     _onChannelError?.Invoke(var1);
 }
示例#25
0
            /// <summary>
            /// Takes two TNumbers and divides one by the other.
            /// </summary>
            /// <param name="interpreter">The interpreter that the method is being called from.</param>
            /// <param name="a">The left hand operand of the operation.</param>
            /// <param name="b">The right hand operand of the operation.</param>
            /// <returns>
            /// The TType resulting from the operation. An MExcpetion or null is returned when there is an error.
            /// </returns>
            public static TType Divide(Interpreter interpreter, TType a, TType b)
            {
                // Try to get TNumber values from the TType arguments
                TNumber    numberA, numberB;
                TException exception = AssignNumberValue(interpreter, out numberA, a);

                if (exception != null)
                {
                    return(exception);
                }
                exception = AssignNumberValue(interpreter, out numberB, b);
                if (exception != null)
                {
                    return(exception);
                }

                // No errors, but one or both of the arguments could be a TString; check them
                if ((numberA == null) || (numberB == null))
                {
                    return(new TException(interpreter, "Strings cannot be used in division operations"));
                }

                switch (numberA.TypeName)
                {
                case TType.T_INTEGER_TYPENAME:
                {
                    // If the other operand is a fraction, treat this integer as a fraction (i.e. value/1)
                    TFraction rhsFraction = numberB as TFraction;
                    if (rhsFraction != null)
                    {
                        // Order of fractions matters in this case
                        TFraction lhsFraction = new TFraction(numberA.TIntegerValue, 1);
                        lhsFraction.Divide(rhsFraction.Numerator, rhsFraction.Denominator);
                        return(lhsFraction);
                    }
                    if (numberB.TypeName == TType.T_INTEGER_TYPENAME)
                    {
                        return(new TFraction(numberA.TIntegerValue, numberB.TIntegerValue));
                    }
                    return(new TInteger(numberA.TIntegerValue / numberB.TIntegerValue));
                }

                case TType.T_REAL_TYPENAME:
                    return(new TReal(numberA.TRealValue / numberB.TRealValue));

                case TType.T_FRACTION_TYPENAME:
                {
                    // Create a copy of the left hand fraction
                    TFraction fraction = numberA as TFraction;
                    fraction = new TFraction(fraction.Numerator, fraction.Denominator);

                    // Convert the right hand operand to a fraction
                    long      numerator, denominator;
                    TFraction otherFraction = numberB as TFraction;
                    if (otherFraction != null)         // If it's a fraction, simply copy the values
                    {
                        numerator   = otherFraction.Numerator;
                        denominator = otherFraction.Denominator;
                    }
                    else
                    {
                        // Check if it's a TInteger first. It might not need to use DoubleToFraction
                        if (numberB is TInteger)
                        {
                            numerator   = numberB.TIntegerValue;
                            denominator = 1;
                        }
                        else
                        {
                            Operations.Misc.DoubleToFraction(numberB.TRealValue, out numerator,
                                                             out denominator);
                        }
                    }

                    fraction.Divide(numerator, denominator);
                    return(fraction);
                }
                }

                return(null);
            }
示例#26
0
 /// <summary>
 /// Throw exception of the given type when
 /// the method is called
 /// </summary>
 /// <typeparam name="TException"></typeparam>
 /// <returns>Fluid Interface</returns>
 IEventOptions IEventOptions.Throws <TException>()
 {
     ThrowsException  = true;
     ExceptionToThrow = new TException();
     return(this);
 }
示例#27
0
            /// <summary>
            /// Takes two TNumbers or two TStrings (or up to two TVariables containing TNumbers or TStrings) and
            /// adds them together.
            /// </summary>
            /// <param name="interpreter">The interpreter that the method is being called from.</param>
            /// <param name="a">The left hand operand of the operation.</param>
            /// <param name="b">The right hand operand of the operation.</param>
            /// <returns>
            /// The TType resulting from the operation. An MExcpetion or null is returned when there is an error.
            /// </returns>
            public static TType Add(Interpreter interpreter, TType a, TType b)
            {
                // Convert arguments 'a' and 'b' into either a TNumber or a TString
                TNumber numberA, numberB;
                TString strA = null, strB = null;

                TException exception = AssignNumberValue(interpreter, out numberA, a);

                if (exception != null)
                {
                    return(exception);
                }

                if (numberA == null)
                {
                    // No errors yet, and numberA is null, so argument 'a' could be a TString or a TVariable
                    // containing a TString
                    strA = a as TString;
                    if (strA == null)
                    {
                        TVariable variable = a as TVariable;
                        if (variable != null)
                        {
                            strA = variable.Value as TString;
                        }
                    }
                }
                if ((numberA == null) && (strA == null)) // Nothing useful, return a TException
                {
                    return(new TException(interpreter, "Value is not a number or string"));
                }


                // Same procedure for argument 'b'
                exception = AssignNumberValue(interpreter, out numberB, b);
                if (exception != null)
                {
                    return(exception);
                }
                if (numberB == null)
                {
                    strB = b as TString;
                    if (strB == null)
                    {
                        TVariable variable = b as TVariable;
                        if (variable != null)
                        {
                            strB = variable.Value as TString;
                        }
                    }
                }
                if ((numberB == null) && (strB == null))
                {
                    return(new TException(interpreter, "Value is not a number or string"));
                }

                // Attempt addition if both operands are the same type, otherwise return a TException
                if ((numberB == null) && (strA == null))
                {
                    return(new TException(interpreter, "Attempted addition of a string to a number"));
                }
                else if ((numberA == null) && (strB == null))
                {
                    return(new TException(interpreter, "Attempted addition of a number to a string"));
                }
                else if ((numberA == null) && (numberB == null))
                {
                    return(new TString(strA.Value + strB.Value));
                }
                else
                {
                    //The left hand operand decides the type of the returned value
                    switch (numberA.TypeName)
                    {
                    case TType.T_INTEGER_TYPENAME:
                    {
                        // If the other operand is a fraction, treat this integer as a fraction (i.e. value/1)
                        TFraction fraction = numberB as TFraction;
                        if (fraction != null)
                        {
                            // Copy the right hand fraction and add the left hand integer to it
                            fraction = new TFraction(fraction.Numerator, fraction.Denominator);
                            fraction.Add(numberA.TIntegerValue, 1);
                            return(fraction);
                        }
                        return(new TInteger(numberA.TIntegerValue + numberB.TIntegerValue));
                    }

                    case TType.T_REAL_TYPENAME:
                        return(new TReal(numberA.TRealValue + numberB.TRealValue));

                    case TType.T_FRACTION_TYPENAME:
                    {
                        // Create a copy of the left hand fraction
                        TFraction fraction = numberA as TFraction;
                        fraction = new TFraction(fraction.Numerator, fraction.Denominator);

                        // Convert the right hand operand to a fraction
                        long      numerator, denominator;
                        TFraction otherFraction = numberB as TFraction;
                        if (otherFraction != null)         // If it's a fraction, simply copy the values
                        {
                            numerator   = otherFraction.Numerator;
                            denominator = otherFraction.Denominator;
                        }
                        else
                        {
                            // Check if it's a TInteger first. It might not need to use DoubleToFraction
                            if (numberB is TInteger)
                            {
                                numerator   = numberB.TIntegerValue;
                                denominator = 1;
                            }
                            else
                            {
                                Operations.Misc.DoubleToFraction(numberB.TRealValue, out numerator,
                                                                 out denominator);
                            }
                        }

                        fraction.Add(numerator, denominator);
                        return(fraction);
                    }
                    }
                }

                return(null);
            }