ASP.NET How to get HttpException ErrorCode - asp.net

I'm trying to catch and handle a specific HttpException, namely "The remote host closed the connection. The error code is 0x800704CD."
My intention is to add a Catch for the HttpException to the relevant Try block and test for the error code that is generated. Sample code:
Try
// Do some stuff
Catch exHttp As HttpException
If exHttp.ErrorCode.ToString() = "0x800704CD" Then DoSomething()
Catch ex As Exception
// Generic error handling
End Try
But I can't work out how to extract the error code displayed in the exception (i.e. "0x800704CD") from the HttpException object. Converting the integer value of the ErrorCode property to hex returns "800704CD" so clearly I'm not understanding how this code is generated.
Thanks.

Try the Below Code:
Try
// Do some stuff
Catch exHttp As HttpException
If exHttp.ErrorCode = &H800704CD Then DoSomething()
Catch ex As Exception
// Generic error handling
End Try

ErrorCode property is an integer so just test for integer value, no reason to convert to hexadecimal or string.
0x in most programming languages means the following characters denote a hexadecimal number, i.e. 0x800704CD means 800704CD will be interpreted as a hexadecimal number. For VB use &H.
More on VB.Net literals:
http://msdn.microsoft.com/en-us/library/s9cz43ek.aspx
http://msdn.microsoft.com/en-us/library/dzy06xhf.aspx

Related

Expected exception is not caught in Unit Test

I have a Unit Test for a class "DbCommand" which in its constructor verifies if the first parameter receives the "?" value. If it does, it throws an ArgumentException.
CONSTRUCTOR PUBLIC DbCommand (dbConnection AS DbConnection,
cInstruction AS CHARACTER):
IF (dbConnection = ?) THEN
UNDO, THROW NEW ArgumentException("DbConnection must be valid":U) .
In the Unit Test I am assigning the first parameter with the "?" to verify that the exception is thrown. For that I added:
#Test (expect="System.ArgumentException").
METHOD PUBLIC VOID TestDbCommand ():
DEFINE VARIABLE oDbCommand AS DbCommand NO-UNDO .
oDbCommand = NEW DbCommand(?, "Delete") .
But the Unit test fails with the first line of the Failure trace being:
"System.ArgumentException: DbConnection must be vaild"
Even though I am already expecting this? I have a few more places were I am using the exact exception and am able to get it caught in the #Test header. But here it doesn't work.
The #Test annotation needs to use the expected attribute, not "expect" for the expected Exception.
And I'm not 100% sure (never used it before), if ABLUnit supports handling of .NET Exceptions in that way - it might be safer to use an ABL Error class instead.

How to handle errors inside Catch block

In my application I am getting System.NullReferenceException for my REST call.
This Error is caused by code inside Catch block.
Is it a good idea to put another try catch block inside Catch block?
In the below code following line of code in Catch block is throwing error.
resultObject.ErrorResponse = _client.GetErrorResponse(Of List(Of ErrorResponseObject))(ex, "{""errors"":")
How do I fix this issue, so that user doesn't see any error.
Here is my code.
Public Shared Function POSTCall()
_client = New BaseClient()
Try
strJsonResponse = _client.ExecuteURI(serviceUrl, requestHeader, "POST", resultObject, False, False)
Catch ex As WebException
resultObject.ErrorResponse = _client.GetErrorResponse(Of List(Of ErrorResponseObject))(ex, "{""errors"":") 'This line causing error
If Not IsNothing(resultObject.ErrorResponse) Then
' do some work
End If
Catch Exp As Exception
'Supress the error. Let user goto next step.
Finally
_client = Nothing
End Try
Return resultObject
End Function
You have to catch the error Inside the catch block. This is especially appropriate since what the code is trying to do is to get more info about an error that has already occurrred. Of course, it might be a good idea to log any error occurring, even if the application can continue.
I prefer doing things that are not asynchronous inside the catch. In a case where I need to perform an asynchronous function say rolling back a database transaction, I'll just throw the error and have another asynchronous function handle it in it's catch block in a synchronous way

Object reference not set to an instance of an object. on Guid.Parse

I have this line of code in my page load.
string sId = Request["sId"];
//couple of more initializations
if (!string.IsNullOrEmpty(sId))
{
Guid GuidThingId = Guid.Parse(sId); //line 73
//method continues.
In my production logs, for some users I see Null Exception at line 73.
Object reference not set to an instance of an object.
Any idea of what's going on?
-Edit-
By looking at the $Guid.Parse$ I see that it can only returns below Exceptions.
// Exceptions:
// System.ArgumentNullException:
// input is null.
//
// System.FormatException:
// input is not in a recognized format.
//
// System.Exception:
// An internal type conversion error occurred.
Try it with Guid.TryParse or Guid.TryParseExact. If your example is correct, Your error is probably internal to the parsing, and your string might not be a valid Guid.
Are you sure you sId is correctly formatted?
Guid GuidThingId = new Guid(sId);

Is there any difference between ex vs ex.ToString? asp.net

I am talking about Try ... Catch ex as Exception .... End Try
If I pass exception to Error Logger, shall I pass exception object (ex) or ex.ToString ? Would I lose any information by passing ex.ToString?
Basically I was arguing with my manager, that ex.ToString should be excatly the same as passing ex as an object. M I wrong or right ?
One is an exception object, one is the string result of calling ToString on an exception object.
They are different types and have different information.
For logging purposes, there is little difference as the logger would normally call ToString on the exception object anyway.
However, it is better to centralize this - have the exception logger call ToString instead of doing this in every call site to the logger. It is more maintainable and opens you up for doing more things with the exceptions in the future if needed.
An exception object is different from calling .ToString() on the object itself. It depends on how much information you want to capture about the exception itself. If you just want the message, then calling .ToString() will be sufficient since that ends up giving you the message property from the exception object. The MSDN site lists different properties that belong to the base exception class. If you want to log any of these properties, then you will want the exception class and not just the message string.
Also note that different classes that inherit the base exception class provide additional information. As an example, the HttpException class provides additional properties. That information could be useful depending on what you need to see to troubleshoot.
An exception object will contain a lot more information than the result of the .ToString(). At the very least that information will be in a more useful format (ie you can get individual pieces easily).
If all you do in the logger is call exception.ToString() though without using anything else then currently it will be no real difference. However, passing the exception object is probably better for future proofing (ie if you start wanting some more properties of the exception).
For what its worth what ToString does is call the following overload passing true as the parameter:
Private Function ToString(ByVal needFileLineInfo As Boolean) As String
Dim className As String
Dim message As String = Me.Message
If ((message Is Nothing) OrElse (message.Length <= 0)) Then
className = Me.GetClassName
Else
className = (Me.GetClassName & ": " & message)
End If
If (Not Me._innerException Is Nothing) Then
className = String.Concat(New String() { className, " ---> ", Me._innerException.ToString(needFileLineInfo), Environment.NewLine, " ", Environment.GetRuntimeResourceString("Exception_EndOfInnerExceptionStack") })
End If
Dim stackTrace As String = Me.GetStackTrace(needFileLineInfo)
If (Not stackTrace Is Nothing) Then
className = (className & Environment.NewLine & stackTrace)
End If
Return className
End Function
As you can see it basically will output the class, message, innerexception.ToString() and stack trace.
Exception object is different than .ToString(). It has vast variety of properties, also if you need to pass the message only, you can use Ex.Message;

Why can't I log an error?

I have an ASP.NET 2010 app. Basically, anywhere I have reason to suspect an error I employ the following technique in order to attempt to log it.
Try
'Code causing error here
Catch ex As Exception When LogException(ex)
Catch ex As Exception 'Here is where I would put a more specific error
End Try
The LogException function ALWAYS returns false. Therefore, every exception should be caught and logged and then control falls back to the next exception in the block. What really happens is the LogException function is called, but before it can do anything, control goes right back to the next exception in the block above. Why?
Edit...Here is the function that is getting called but returning fter the 1st line...
Public Function LogException(ByVal ex As Exception) As Boolean
Dim oExceptionMgt As New ExceptionMgt 'This line runs
oExceptionMgt.LogException(ex) 'This line should go to db to log error.
Return False
End Function
While I am not a VB programmer if I see a condition such as:
do something when somecondition
That logically says only do something when somecondition is true. Therefore in your example the code is executing correctly because your LogException(Exception ex) method is always false. Which in turn means don't do the something in this instance and continue executing.

Resources