示例#1
0
        /// <summary>
        /// Gets the HRESULT of the specified exception.
        /// </summary>
        /// <param name="exception">The exception to test. May not be null.</param>
        /// <param name="defaultValue">The default value in case of an error.</param>
        /// <returns>The HRESULT value.</returns>
        /// <remarks>code from http://stackoverflow.com/questions/50744/wait-until-file-is-unlocked-in-net </remarks>
        public static int GetHResult(IOException exception, int defaultValue)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            try
            {
                const string name = "HResult";
                PropertyInfo pi   = exception.GetType().GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance); // CLR2

                if (pi == null)
                {
                    pi = exception.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance); // CLR4
                }

                if (pi != null)
                {
                    return((int)pi.GetValue(exception, null));
                }
            }
            catch
            {
            }
            return(defaultValue);
        }
示例#2
0
 private PostEditorStorageException(IOException ex)
     : base(StringId.PostEditorStorageExceptionTitle2,
            StringId.PostEditorStorageExceptionMessage2,
            ex.GetType().Name,
            ex.Message)
 {
 }
示例#3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSurfaceTaskErrorInAssertHealthy() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSurfaceTaskErrorInAssertHealthy()
        {
            // GIVEN
            TaskExecutor <Void> executor  = new DynamicTaskExecutor <Void>(2, 0, 10, _park, this.GetType().Name);
            IOException         exception = new IOException("Failure");

            // WHEN
            FailingTask failingTask = new FailingTask(exception);

            executor.Submit(failingTask);
            failingTask.Latch.await();
            failingTask.Latch.release();

            // WHEN
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    executor.AssertHealthy();
                    // OK, so the executor hasn't executed the finally block after task was done yet
                    Thread.Sleep(100);
                }
                catch (Exception e)
                {
                    assertTrue(Exceptions.contains(e, exception.Message, exception.GetType()));
                    return;
                }
            }
            fail("Should not be considered healthy after failing task");
        }
示例#4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCloseTransactionRegardlessOfWhetherOrNotItAppliedCorrectly() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldCloseTransactionRegardlessOfWhetherOrNotItAppliedCorrectly()
        {
            // GIVEN
            TransactionIdStore  transactionIdStore = mock(typeof(TransactionIdStore));
            TransactionAppender appender           = new TestableTransactionAppender(transactionIdStore);
            long txId = 11;

            when(transactionIdStore.NextCommittingTransactionId()).thenReturn(txId);
            IOException   rootCause     = new IOException("Mock exception");
            StorageEngine storageEngine = mock(typeof(StorageEngine));

            doThrow(new IOException(rootCause)).when(storageEngine).apply(any(typeof(TransactionToApply)), any(typeof(TransactionApplicationMode)));
            TransactionCommitProcess commitProcess = new TransactionRepresentationCommitProcess(appender, storageEngine);
            TransactionToApply       transaction   = MockedTransaction();

            // WHEN
            try
            {
                commitProcess.Commit(transaction, _commitEvent, INTERNAL);
            }
            catch (TransactionFailureException e)
            {
                assertThat(e.Message, containsString("Could not apply the transaction to the store"));
                assertTrue(contains(e, rootCause.Message, rootCause.GetType()));
            }

            // THEN
            // we can't verify transactionCommitted since that's part of the TransactionAppender, which we have mocked
            verify(transactionIdStore, times(1)).transactionClosed(eq(txId), anyLong(), anyLong());
        }
示例#5
0
        public virtual void TestNestedException()
        {
            Exception            e   = new NoRouteToHostException("that box caught fire 3 years ago");
            Exception            ioe = new IOException("Datacenter problems", e);
            ThrowableInformation ti  = new ThrowableInformation(ioe);
            Log4Json             l4j = new Log4Json();
            long   timeStamp         = Time.Now();
            string outcome           = l4j.ToJson(new StringWriter(), "testNestedException", timeStamp,
                                                  "INFO", "quoted\"", "new line\n and {}", ti).ToString();

            Println("testNestedException", outcome);
            ContainerNode rootNode = Log4Json.Parse(outcome);

            AssertEntryEquals(rootNode, Log4Json.Level, "INFO");
            AssertEntryEquals(rootNode, Log4Json.Name, "testNestedException");
            AssertEntryEquals(rootNode, Log4Json.Time, timeStamp);
            AssertEntryEquals(rootNode, Log4Json.ExceptionClass, ioe.GetType().FullName);
            JsonNode node = AssertNodeContains(rootNode, Log4Json.Stack);

            Assert.True("Not an array: " + node, node.IsArray());
            node = AssertNodeContains(rootNode, Log4Json.Date);
            Assert.True("Not a string: " + node, node.IsTextual());
            //rather than try and make assertions about the format of the text
            //message equalling another ISO date, this test asserts that the hypen
            //and colon characters are in the string.
            string dateText = node.GetTextValue();

            Assert.True("No '-' in " + dateText, dateText.Contains("-"));
            Assert.True("No '-' in " + dateText, dateText.Contains(":"));
        }
示例#6
0
        /// <exception cref="System.Exception"/>
        public virtual void TestSerializedExceptionDeSer()
        {
            // without cause
            YarnException       yarnEx    = new YarnException("Yarn_Exception");
            SerializedException serEx     = SerializedException.NewInstance(yarnEx);
            Exception           throwable = serEx.DeSerialize();

            NUnit.Framework.Assert.AreEqual(yarnEx.GetType(), throwable.GetType());
            NUnit.Framework.Assert.AreEqual(yarnEx.Message, throwable.Message);
            // with cause
            IOException      ioe = new IOException("Test_IOException");
            RuntimeException runtimeException = new RuntimeException("Test_RuntimeException",
                                                                     ioe);
            YarnException       yarnEx2    = new YarnException("Test_YarnException", runtimeException);
            SerializedException serEx2     = SerializedException.NewInstance(yarnEx2);
            Exception           throwable2 = serEx2.DeSerialize();

            Sharpen.Runtime.PrintStackTrace(throwable2);
            NUnit.Framework.Assert.AreEqual(yarnEx2.GetType(), throwable2.GetType());
            NUnit.Framework.Assert.AreEqual(yarnEx2.Message, throwable2.Message);
            NUnit.Framework.Assert.AreEqual(runtimeException.GetType(), throwable2.InnerException
                                            .GetType());
            NUnit.Framework.Assert.AreEqual(runtimeException.Message, throwable2.InnerException
                                            .Message);
            NUnit.Framework.Assert.AreEqual(ioe.GetType(), throwable2.InnerException.InnerException
                                            .GetType());
            NUnit.Framework.Assert.AreEqual(ioe.Message, throwable2.InnerException.InnerException
                                            .Message);
        }
示例#7
0
        /// ------------------------------------------------------------------------------------------------
        #region Public Constructor
        /// ------------------------------------------------------------------------------------------------
        ///
        /// ------------------------------------------------------------------------------------------------
        /// Name		ErrorReport
        ///
        /// <summary>	Creates a new instance of the ErrorReport class instantiated from an
        ///             unmanaged native exception.
        /// </summary>
        /// <param name="title">		The title for the report.</param>
        /// <param name="ex">			The exception details.</param>
        ///
        /// <remarks>
        /// </remarks>
        /// ------------------------------------------------------------------------------------------------
        ///
        public ErrorReport(string title, IOException ex)
        {
            try
            {
                StringBuilder sb;
                //
                sb = new StringBuilder();
                sb.AppendLine(title);
                sb.AppendLine();
                sb.AppendLine("Exception:");
                sb.AppendLine(ex.GetType().ToString());
                sb.AppendLine(ex.Message);
                sb.AppendLine();
                sb.AppendLine("Stack Trace:");
                if (ex.StackTrace != null)
                {
                    foreach (char s in ex.StackTrace)
                    {
                        sb.AppendLine(s.ToString());
                    }
                }

                Serialised = sb.ToString();
            }
            catch (Exception e)
            {
                LogTracking.LogTrace(e.ToString());
            }
        }
        public static string GetFileReadExplanation(IOException ex)
        {
            string explanation = "The following error occured:";

            explanation += "The file" + ex.GetType().Name + " Could not be read and load." + ex.Message;

            return(explanation);
        }
 public BlogClientIOException(FileInfo file, IOException ioException)
     : base(StringId.BCEFileIOTitle,
            StringId.BCEFileIOMessage,
            file.Name,
            ioException.GetType().Name,
            ioException.Message)
 {
 }
示例#10
0
 public BlogClientIOException(string context, IOException ioException)
     : base(StringId.BCENetworkIOTitle,
            StringId.BCENetworkIOMessage,
            context,
            ioException.GetType().Name,
            ioException.Message)
 {
 }
示例#11
0
        /// <exception cref="System.Exception"/>
        private IOException VerifyExceptionClass(IOException e, Type expectedClass)
        {
            NUnit.Framework.Assert.IsNotNull("Null Exception", e);
            IOException wrapped = NetUtils.WrapException("desthost", DestPort, "localhost", LocalPort
                                                         , e);

            Log.Info(wrapped.ToString(), wrapped);
            if (!(wrapped.GetType().Equals(expectedClass)))
            {
                throw Extensions.InitCause(new AssertionFailedError("Wrong exception class; expected "
                                                                    + expectedClass + " got " + wrapped.GetType() + ": " + wrapped), wrapped);
            }
            return(wrapped);
        }
示例#12
0
        /// <summary>Converts an IOExcpetion (not subclasses) to SocketException.</summary>
        /// <remarks>
        /// Converts an IOExcpetion (not subclasses) to SocketException.
        /// This is typically done to indicate to upper layers that the error
        /// was a socket error rather than often more serious exceptions like
        /// disk errors.
        /// </remarks>
        private static IOException IoeToSocketException(IOException ioe)
        {
            if (ioe.GetType().Equals(typeof(IOException)))
            {
                // "se" could be a new class in stead of SocketException.
                IOException se = new SocketException("Original Exception : " + ioe);
                Sharpen.Extensions.InitCause(se, ioe);

                /* Change the stacktrace so that original trace is not truncated
                 * when printed.*/
                se.SetStackTrace(ioe.GetStackTrace());
                return(se);
            }
            // otherwise just return the same exception.
            return(ioe);
        }
示例#13
0
        /// <summary>
        /// Verifies whether the IOException corresponds to "There is not enough space on the disk" error.
        /// Using the HResult value (-2147024784 - ERROR_DISK_FULL)to determine "Disk out of space"
        /// </summary>
        /// <param name="ioException"></param>
        /// <returns>True if the exception corresponds to "There is not enough space on the disk" error
        /// else false</returns>
        internal static bool IsDiskOutOfSpaceError(IOException ioException)
        {
            // HResult is a protected memeber defined in the base Exception class. Using reflection
            // to retrieve this value
            Type         exceptionType   = ioException.GetType();
            PropertyInfo hResultProperty = exceptionType.GetProperty("HResult", BindingFlags.Instance | BindingFlags.NonPublic);

            if (hResultProperty != null)
            {
                int hResultValue = (int)hResultProperty.GetValue(ioException, null);
                if (-2147024784 == hResultValue)
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
        /// if the given method should be retried.
        /// </summary>
        /// <remarks>
        /// Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
        /// if the given method should be retried.
        /// </remarks>
        public virtual bool RetryRequest(IOException exception, int executionCount, HttpContext
                                         context)
        {
            Args.NotNull(exception, "Exception parameter");
            Args.NotNull(context, "HTTP context");
            if (executionCount > this.retryCount)
            {
                // Do not retry if over max retry count
                return(false);
            }
            if (this.nonRetriableClasses.Contains(exception.GetType()))
            {
                return(false);
            }
            else
            {
                foreach (Type rejectException in this.nonRetriableClasses)
                {
                    if (rejectException.IsInstanceOfType(exception))
                    {
                        return(false);
                    }
                }
            }
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            IHttpRequest request = clientContext.GetRequest();

            if (RequestIsAborted(request))
            {
                return(false);
            }
            if (HandleAsIdempotent(request))
            {
                // Retry if the request is considered idempotent
                return(true);
            }
            if (!clientContext.IsRequestSent() || this.requestSentRetryEnabled)
            {
                // Retry if the request has not been sent fully or
                // if it's OK to retry methods that have been sent
                return(true);
            }
            // otherwise do not retry
            return(false);
        }
 static int GetHResult(IOException ioe, int defaultValue)
 {
     if (ioe == null)
     {
         throw new ArgumentNullException("ioe");
     }
     try
     {
         return((int)ioe.GetType()
                .GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(ioe, null));
     }
     catch
     {
         return(defaultValue);
     }
 }
示例#16
0
        /// ------------------------------------------------------------------------------------------------
        /// Name        ErrorReport
        ///
        /// <summary>   Creates a new instance of the ErrorReport class instantiated from an
        ///             unmanaged native exception.
        /// </summary>
        /// <param name="title">        The title for the report.</param>
        /// <param name="ex">           The exception details</param>
        /// ------------------------------------------------------------------------------------------------
        public ErrorReport(string title, IOException ex)
        {
            StringBuilder sb;

            sb = new StringBuilder();
            sb.AppendLine(title);
            sb.AppendLine();
            sb.AppendLine("Exception:");
            sb.AppendLine(ex.GetType().ToString());
            sb.AppendLine(ex.Message);
            sb.AppendLine();
            sb.AppendLine("Stack Trace:");
            if (ex.StackTrace != null)
            {
                sb.AppendLine(ex.StackTrace);
            }

            Serialised = sb.ToString();
        }
示例#17
0
        private static bool handleIOException(IOException ex, MethodBase Method)
        {
            Logging.Logger("ERROR:  MethodName=" + Method.Name + "  Type: " + ex.GetType().Name + "  #:" + ex.HResult + "  Message:" + ex.Message);
            switch (ex.HResult)
            {
            case -2147024864:
                return(true);

            case -2147024843:     // Network path not found.
                return(true);

            case -2146232800:
                return(true);

            default:
                UnHandledError(ex, ex.HResult, Method);
                break;
            }
            return(false);
        }
示例#18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailWithProperMessageOnAppendException() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldFailWithProperMessageOnAppendException()
        {
            // GIVEN
            TransactionAppender appender  = mock(typeof(TransactionAppender));
            IOException         rootCause = new IOException("Mock exception");

            doThrow(new IOException(rootCause)).when(appender).append(any(typeof(TransactionToApply)), any(typeof(LogAppendEvent)));
            StorageEngine            storageEngine = mock(typeof(StorageEngine));
            TransactionCommitProcess commitProcess = new TransactionRepresentationCommitProcess(appender, storageEngine);

            // WHEN
            try
            {
                commitProcess.Commit(MockedTransaction(), _commitEvent, INTERNAL);
                fail("Should have failed, something is wrong with the mocking in this test");
            }
            catch (TransactionFailureException e)
            {
                assertThat(e.Message, containsString("Could not append transaction representation to log"));
                assertTrue(contains(e, rootCause.Message, rootCause.GetType()));
            }
        }
示例#19
0
        public static int GetExceptionHResult(IOException ex)
        {
            PropertyInfo hResult = ex.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            return((int)hResult.GetValue(ex, null));
        }
示例#20
0
 private static IActionResult HandleIOException(IOException e)
 {
     Console.WriteLine(e);
     return(new ObjectResult($"The map repo is not accessible. ({e.GetType().Name} : {e.Message}"));
 }
示例#21
0
文件: Util.cs 项目: Neo4Net/Neo4Net
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void wrapIOException(java.io.IOException e) throws org.neo4j.commandline.admin.CommandFailed
        public static void WrapIOException(IOException e)
        {
            throw new CommandFailed(format("unable to load database: %s: %s", e.GetType().Name, e.Message), e);
        }
示例#22
0
        public static void MyDeleteFolder(Task buildTask, string folderName, DeleteDirectoryOption OnDirectoryNotEmpty, bool failOnError, string logText)
        {
            var myComputer = new Computer();

            if (Directory.Exists(folderName))
            {
                if (Strings.Len(logText) > 0)
                {
                    MyLogMessage(buildTask, string.Format(logText, folderName), MessageImportance.Normal);
                }
                try
                {
                    myComputer.FileSystem.DeleteDirectory(folderName, OnDirectoryNotEmpty);
                }
                catch (UnauthorizedAccessException exception1)
                {
                    ProjectData.SetProjectError(exception1);
                    UnauthorizedAccessException exception = exception1;
                    if (OnDirectoryNotEmpty == DeleteDirectoryOption.DeleteAllContents)
                    {
                        foreach (string str in Directory.GetFiles(folderName, "*.*", System.IO.SearchOption.AllDirectories))
                        {
                            MyDeleteFile(str, true);
                        }
                        MyDeleteFolder(buildTask, folderName, DeleteDirectoryOption.ThrowIfDirectoryNonEmpty, failOnError, logText);
                    }
                    ProjectData.ClearProjectError();
                }
                catch (IOException exception4)
                {
                    ProjectData.SetProjectError(exception4);
                    IOException exception2 = exception4;
                    if ((Strings.InStr(exception2.Message, "is not empty", CompareMethod.Binary) > 0) && (OnDirectoryNotEmpty == DeleteDirectoryOption.DeleteAllContents))
                    {
                        foreach (string str2 in Directory.GetDirectories(folderName, "*", System.IO.SearchOption.TopDirectoryOnly))
                        {
                            MyDeleteFolder(buildTask, str2, DeleteDirectoryOption.ThrowIfDirectoryNonEmpty, failOnError, logText);
                        }
                    }
                    else
                    {
                        if (failOnError)
                        {
                            throw;
                        }
                        MyLogWarning(buildTask, string.Format("Deleting folder '{0}' failed with exception '{1}'. The exception type was '{2}'. This may result in a later build error.", folderName, exception2.Message, exception2.GetType().Name));
                    }
                    ProjectData.ClearProjectError();
                }
                catch (Exception exception5)
                {
                    ProjectData.SetProjectError(exception5);
                    Exception exception3 = exception5;
                    if (failOnError)
                    {
                        throw;
                    }
                    MyLogWarning(buildTask, string.Format("Deleting folder '{0}' failed with exception '{1}'. The exception type was '{2}'. This may result in a later build error.", folderName, exception3.Message, exception3.GetType().Name));
                    ProjectData.ClearProjectError();
                }
            }
        }