Ejemplo n.º 1
0
        public static void TestAxCryptExceptionSerialization()
        {
            FileFormatException ffe = new FileFormatException("A test-exception");
            IFormatter ffeFormatter = new BinaryFormatter();
            using (Stream stream = new MemoryStream())
            {
                ffeFormatter.Serialize(stream, ffe);
                stream.Position = 0;
                FileFormatException deserializedFfe = (FileFormatException)ffeFormatter.Deserialize(stream);
                Assert.That(deserializedFfe.ErrorStatus, Is.EqualTo(ErrorStatus.FileFormatError), "The deserialized status should be the same as the original.");
                Assert.That(deserializedFfe.Message, Is.EqualTo("A test-exception"), "The deserialized message should be the same as the original.");
            }

            InternalErrorException iee = new InternalErrorException("A test-exception", ErrorStatus.InternalError);
            IFormatter ieeFormatter = new BinaryFormatter();
            using (Stream stream = new MemoryStream())
            {
                ieeFormatter.Serialize(stream, iee);
                stream.Position = 0;
                InternalErrorException deserializedFfe = (InternalErrorException)ieeFormatter.Deserialize(stream);
                Assert.That(deserializedFfe.ErrorStatus, Is.EqualTo(ErrorStatus.InternalError), "The deserialized status should be the same as the original.");
                Assert.That(deserializedFfe.Message, Is.EqualTo("A test-exception"), "The deserialized message should be the same as the original.");
            }

            Axantum.AxCrypt.Core.Runtime.InvalidDataException ide = new Axantum.AxCrypt.Core.Runtime.InvalidDataException("A test-exception");
            IFormatter ideFormatter = new BinaryFormatter();
            using (Stream stream = new MemoryStream())
            {
                ideFormatter.Serialize(stream, ide);
                stream.Position = 0;
                Axantum.AxCrypt.Core.Runtime.InvalidDataException deserializedFfe = (Axantum.AxCrypt.Core.Runtime.InvalidDataException)ideFormatter.Deserialize(stream);
                Assert.That(deserializedFfe.ErrorStatus, Is.EqualTo(ErrorStatus.DataError), "The deserialized status should be the same as the original.");
                Assert.That(deserializedFfe.Message, Is.EqualTo("A test-exception"), "The deserialized message should be the same as the original.");
            }
        }
Ejemplo n.º 2
0
 public void CheckForBinanceException(int statusCode, String body)
 {
     if (statusCode >= 200 && statusCode <= 299)
     {
         return;
     }
     else if (statusCode == 429)
     {
         throw RateLimitedException.CreateFromPayload(body);
     }
     else if (statusCode == 418)
     {
         throw IpBannedException.CreateFromPayload(body);
     }
     else if (statusCode >= 400 && statusCode <= 499)
     {
         throw MalformedRequestException.CreateFromPayload(body);
     }
     else if (statusCode >= 500 && statusCode <= 599)
     {
         throw InternalErrorException.CreateFromPayload(body);
     }
     else
     {
         throw new BinanceException(0, body);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Decrypts the header part of specified source stream.
        /// </summary>
        /// <param name="source">The source stream.</param>
        /// <param name="decryptionParameters">The decryption parameters.</param>
        /// <param name="displayContext">The display context.</param>
        /// <param name="progress">The progress.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// source
        /// or
        /// decryptionParameters
        /// or
        /// progress
        /// </exception>
        private static IAxCryptDocument Document(Stream source, IEnumerable <DecryptionParameter> decryptionParameters, string displayContext, IProgressContext progress)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (decryptionParameters == null)
            {
                throw new ArgumentNullException("decryptionParameters");
            }
            if (progress == null)
            {
                throw new ArgumentNullException("progress");
            }

            try
            {
                IAxCryptDocument document = New <AxCryptFactory>().CreateDocument(decryptionParameters, new ProgressStream(source, progress));
                return(document);
            }
            catch (AxCryptException ace)
            {
                ace.DisplayContext = displayContext;
                throw;
            }
            catch (Exception ex)
            {
                AxCryptException ace = new InternalErrorException("An unhandled exception occurred.", Abstractions.ErrorStatus.Unknown, ex);
                ace.DisplayContext = displayContext;
                throw ace;
            }
        }
Ejemplo n.º 4
0
        private void HandleResponseMessage(ResponseMessage responseMessage, string debugData)
        {
            if (!PendingMessages.TryRemove(responseMessage.Id, out var pm))
            {
                // got the unknown answer message
                // cannot throw here because we're on the worker thread
                var ex    = new InternalErrorException($"Got a response for the unknown message #{responseMessage.Id}: {debugData}");
                var eargs = new ThreadExceptionEventArgs(ex);
                UnhandledException?.Invoke(this, eargs);
                return;
            }

            var tcs = pm.CompletionSource;

            // signal the remote exception
            if (responseMessage.Error != null)
            {
                var exception = JsonServicesException.Create(responseMessage.Error);
                tcs.TrySetException(exception);
                return;
            }

            // signal the result
            tcs.TrySetResult(responseMessage.Result);
        }
Ejemplo n.º 5
0
 public ParserException(InternalErrorException e, string reference)
 {
     this.message     = "Internal Error";
     this.reference   = reference;
     this.description = e.Message;
     this.Parse(e.DecoratedMessage);
 }
Ejemplo n.º 6
0
        public static Exception Fail([Localizable(false)] string?message, Exception?innerException)
        {
            var  exception = new InternalErrorException(message, innerException);
            bool proceed   = true; // allows debuggers to skip the throw statement

            if (proceed)
            {
                throw exception;
            }
            else
            {
                return(new Exception());
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Throws an public exception.
        /// </summary>
        /// <returns>Nothing, as this method always throws.  The signature allows for "throwing" Fail so C# knows execution will stop.</returns>
        public static Exception Fail([Localizable(false)] string message, Exception innerException, bool showAssert = true)
        {
            var  exception = new InternalErrorException(message, innerException, showAssert);
            bool proceed   = true; // allows debuggers to skip the throw statement

            if (proceed)
            {
                throw exception;
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 8
0
        public static T NotReachable <T>()
        {
            // Keep these two as separate lines of code, so the debugger can come in during the assert dialog
            // that the exception's constructor displays, and the debugger can then be made to skip the throw
            // in order to continue the investigation.
            var exception = new InternalErrorException();

            bool proceed = true; // allows debuggers to skip the throw statement

            if (proceed)
            {
                throw exception;
            }
            else
            {
#pragma warning disable CS8763 // A method marked [DoesNotReturn] should not return.
                return(default);
Ejemplo n.º 9
0
        public static Exception NotReachable()
        {
            // Keep these two as separate lines of code, so the debugger can come in during the assert dialog
            // that the exception's constructor displays, and the debugger can then be made to skip the throw
            // in order to continue the investigation.
            var  exception = new InternalErrorException();
            bool proceed   = true; // allows debuggers to skip the throw statement

            if (proceed)
            {
                throw exception;
            }
            else
            {
                return(new Exception());
            }
        }
Ejemplo n.º 10
0
        public static Exception Fail([Localizable(false)] string?message = null)
        {
            var  exception = new InternalErrorException(message);
            bool proceed   = true; // allows debuggers to skip the throw statement

            if (proceed)
            {
                throw exception;
            }
            else
            {
#pragma warning disable CS8763
                return(new Exception());

#pragma warning restore CS8763
            }
        }
Ejemplo n.º 11
0
        public static ServiceException ConvertException(Exception ex)
        {
            ServiceException result;

            switch (ex)
            {
            case ArgumentNullException argumentNullException:
            {
                result = new MissingArgumentException(
                    message: "Request is missing argument.",
                    innerException: argumentNullException);
                break;
            }

            case ArgumentException argumentException:
            {
                result = new InvalidArgumentException(
                    message: "Request has an invalid argument.",
                    innerException: argumentException);
                break;
            }

            case ServiceException serviceException:
            {
                result = serviceException;
                break;
            }

            default:
            {
                result = new InternalErrorException(
                    message: "An internal error has occurred.",
                    innerException: ex);
                break;
            }
            }

            return(result);
        }
Ejemplo n.º 12
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(InternalErrorException obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Handle request request and get the response
        /// </summary>
        /// <param name="service">The service which will handle the request.</param>
        /// <param name="request">The request to handle.</param>
        /// <returns>The response for the request.</returns>
        protected async Task <JsonRpcResponse> GetResponseAsync(JsonRpcService service, JsonRpcRequest request)
        {
            JsonRpcResponse response = null;

            try
            {
                var rpcCall = service.GetRpcCall(request.Method);
                if (rpcCall == null)
                {
                    throw new MethodNotFoundException($"Method: {request.Method} not found.");
                }
                var arguments = await JsonRpcCodec.DecodeArgumentsAsync(request.Params, rpcCall.Parameters).ConfigureAwait(false);

                //From here we got the response id.
                response = new JsonRpcResponse(request.Id);
                //The parser will add context into the args, so the final count is parameter count + 1.
                if (arguments.Length == rpcCall.Parameters.Count)
                {
                    try
                    {
                        var result = await rpcCall.Call(arguments).ConfigureAwait(false);

                        if (request.IsNotification)
                        {
                            return(null);
                        }
                        response.WriteResult(result);
                    }
                    catch (Exception ex)
                    {
                        var argumentString = new StringBuilder();
                        argumentString.Append(Environment.NewLine);
                        var index = 0;
                        foreach (var argument in arguments)
                        {
                            argumentString.AppendLine($"[{index}] {argument}");
                        }

                        argumentString.Append(Environment.NewLine);
                        Logger.WriteError($"Call method {rpcCall.Name} with args:{argumentString} error :{ex.Format()}");
                        response.WriteResult(new InternalErrorException());
                    }
                }
                else
                {
                    throw new InvalidParamsException("Argument count is not matched");
                }
            }
            catch (Exception ex)
            {
                response ??= new JsonRpcResponse();
                if (ex is RpcException rpcException)
                {
                    Logger.WriteError($"Handle request {request} error: {rpcException.Format()}");
                    response.WriteResult(rpcException);
                }
                else
                {
                    Logger.WriteError($"Handle request {request} error: {ex.Format()}");
                    var serverError = new InternalErrorException();
                    response.WriteResult(serverError);
                }
            }
            return(response);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Handle connected request and return result.
        /// </summary>
        /// <param name="context">The http context to handle.</param>
        /// <param name="router">The router to dispatch the request data.</param>
        /// <param name="cancellationToken">The cancellation token which can cancel this method.</param>
        /// <returns>Void</returns>
        protected async Task HandleContextAsync(IJsonRpcHttpContext context, IJsonRpcRouter router, CancellationToken cancellationToken = default)
        {
            var httpMethod  = context.GetRequestHttpMethod();
            var requestPath = context.GetRequestPath();

            Logger.WriteVerbose($"Handle request [{httpMethod}]: {requestPath}");
            try
            {
                var serviceName = GetRpcServiceName(requestPath);
                if (string.IsNullOrEmpty(serviceName))
                {
                    Logger.WriteWarning($"Service for request: {requestPath} not found.");
                    throw new HttpException((int)HttpStatusCode.ServiceUnavailable, "Service does not exist.");
                }

                if (httpMethod == "get")
                {
                    var smdRequest = false;
                    var smdIndex   = serviceName.LastIndexOf(".smd", StringComparison.InvariantCultureIgnoreCase);
                    if (smdIndex != -1)
                    {
                        serviceName = serviceName.Substring(0, smdIndex);
                        smdRequest  = true;
                    }

                    if (!router.ServiceExists(serviceName))
                    {
                        Logger.WriteWarning($"Service for request: {requestPath} not found.");
                        throw new HttpException((int)HttpStatusCode.ServiceUnavailable, $"Service [{serviceName}] does not exist.");
                    }

                    if (SmdEnabled && smdRequest)
                    {
                        try
                        {
                            var smdData = await router.GetServiceSmdData(serviceName);
                            await WriteSmdDataAsync(context, smdData, cancellationToken).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            throw new HttpException((int)HttpStatusCode.InternalServerError, ex.Message);
                        }
                    }
                    else
                    {
                        throw new HttpException((int)HttpStatusCode.NotFound, $"Resource for {requestPath} does not exist.");
                    }
                }
                else if (httpMethod == "post")
                {
                    if (!router.ServiceExists(serviceName))
                    {
                        Logger.WriteWarning($"Service for request: {requestPath} not found.");
                        throw new ServerErrorException("Service does not exist.", $"Service [{serviceName}] does not exist.");
                    }

                    try
                    {
                        await DispatchAsync(context, router, serviceName, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        if (ex is RpcException)
                        {
                            throw;
                        }

                        throw new ServerErrorException("Internal server error.", ex.Message);
                    }
                }
                else
                {
                    throw new HttpException((int)HttpStatusCode.MethodNotAllowed, $"Invalid http-method:{httpMethod}");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError($"Handle request {requestPath} error: {ex.Message}");
                if (ex is HttpException httpException)
                {
                    await WriteHttpExceptionAsync(context, httpException, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    var response = new JsonRpcResponse();
                    if (ex is RpcException rpcException)
                    {
                        response.WriteResult(rpcException);
                    }
                    else
                    {
                        var serverError =
                            new InternalErrorException($"Handle request {requestPath} error: {ex.Message}");
                        response.WriteResult(serverError);
                    }

                    await WriteRpcResponsesAsync(context, new[] { response }, cancellationToken).ConfigureAwait(false);
                }
            }
            finally
            {
                context.Close();
            }
        }