I have the following code:
Public Function UltimoIngreso() As Date
Try
UltimoIngreso = Now.Date 'I am not ALWAYS getting the current date and time
' --other lines of code
Catch ex As Exception
' An error has occured so display an error message.
ReportBDLog.ReportErrorBD(ex, Me.GetType.ToString & "." & "UltimoIngreso" & vbCrLf & "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf, System.Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Function
Sometimes, but not always, I get "Object reference not set to an instance of an object."
How do I ensure that Function UltimoIngreso always returns current date and time?
What am I missing?
This Function is used in an asp.net App.
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
My code updates & inserts into a bunch of tables. About 2 months ago I got the same error as the one below, I assumed it was because the exception it self is Nothing.
So I built in a test to check if it isn't nothing, write the exception details.
However, the error in the screenshot occurred again this morning. My question now is how does a code block like the one below result in the Exception being Null, and in which cases will an exception be Null?
Edited - This is different to this question because I want to know how an EXCEPTION can be Null/Nothing
Try
If t.DpaPosted = "N" Then
i += 1
OutputCount += 1
Dim SubAccountID As Integer = 0
If t.SubaccountId = 0 Then
SubAccountID = GetSubAccountID(t.DpaInId)
If SubAccountID = 0 Then
If DupAcc > 1 Then
UpdateLog(t.clientReference & " - Multiple CLOSED(Paid Up/Refunds outstanding) accounts.")
Else
SubAccountID = GetClosedSubAccountID(t.DpaInID)
If SubAccountID = 0 Then
UpdateLog(t.clientReference & " - No accounts found.")
End If
End If
End If
End If
If SubAccountID <> 0 Then
If t.DpaDocNo <> "0" Then
If q.Execquery("SELECT COUNT(1) FROM Transactions WHERE SubAccountID = " & t.SubaccountId & " AND TranTypeID = 6 AND TranAmount = " & t.DpaAmount & " AND DPANo = '" & t.DpaDocNo & "'") > 0 Then
HttpContext.Current.Response.Write("Sequence [" & t.DpaDocNo & "] already posted.<br/>")
dpaadapter.SetDpaPosted(t.DpaInId)
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
End If
If WriteOutput Then HttpContext.Current.Response.Write("Imported [" + i.ToString + "] of [" + dpa.Rows.Count.ToString + "]<br/>")
If OutputCount = 10 Then
OutputCount = 0
If WriteOutput Then
If HttpContext.Current.Response.IsClientConnected Then
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Write("<script>window.scrollTo(0,document.body.scrollHeight);</script>")
HttpContext.Current.Response.Flush()
End If
End If
End If
End If
Catch ex As Exception
Dim LogStr As String = ""
LogStr = "Record [" & i.ToString & "]. "
LogStr = "Ref [" & t.clientReference & "] - "
If ex.Message.ToString <> Nothing Then LogStr = LogStr & ex.Message.ToString Else LogStr = LogStr & "No Exception Message"
If ex.InnerException.ToString <> Nothing Then LogStr = LogStr & vbCrLf & ex.InnerException.ToString Else LogStr = LogStr & "No Inner Exception"
UpdateLog(LogStr)
SaveLog()
End Try
I can't actually see what code is triggering the exception, until I can fix the exception handling.
Some more information that might help
I am using asp.net V 4.0
The code is in a class, and the file is located in the appcode directory.
The issue doesn't always trigger
When running the code for a second/third time, the exception doesn't trigger again. So I can't recreate the error all the time.
Windows event viewer didn't log any exceptions for this page.
ANSWER
Found from this question.
An inner exception is the exception that caused the current exception.
It is used in cases when you want to surface a different exception
than the one that your code caught but you don't want to throw away
the original context.
In order for a new exception to have information about a previous one,
like you said, you pass it as constructor parameter to the new one.
Usually, a null inner exception means that the current exception is
root cause of the exceptional situation.
How about safeguarding your ex.InnerException? Once you make sure that an InnerException exists then you can access its methods and properties.
If ex.InnerException Is Not Nothing AndAlso ... Then
See this explanation (and read the accepted answer) about InnerException. It is not necessary to have an InnerException, unless the current exception was caused by another exception.
It might be a little funny but I am facing some stupid issue.
I am using
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
and
Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
when I using this the error is given to me is "Could not find a part of the path "
If am storing the path in a string then its working fine else producing error.
For your reference I am copying my function code snippet.
Please help
Thanks
Public Shared Function LogErrorToLogFile(ByVal ee As Exception, ByVal userFriendlyError As String) As String
Try
Dim path As String = context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))
' check if directory exists
If Not Directory.Exists(path) Then
'Directory.CreateDirectory(path)
Directory.CreateDirectory(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
End If
path = path & DateTime.Today.ToString("dd-MMM-yy") & ".log"
' check if file exist
If Not File.Exists(path) Then
File.Create(path).Dispose()
'File.Create(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))).Dispose()
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
End If
' log the error now
Using writer As StreamWriter = File.AppendText(path)
'Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
writer.WriteLine(HttpUtility.HtmlEncode(vbCr & vbLf & "Log written at : " & DateTime.Now.ToString() & vbCr & vbLf & "Error occured on page : " & context.Current.Request.Url.ToString() & vbCr & vbLf & vbCr & vbLf & "Here is the actual error :" & vbLf & ee.ToString()))
writer.WriteLine("==========================================")
writer.Flush()
writer.Close()
End Using
Return userFriendlyError
Catch
Throw
End Try
End Function
If you change the current lines with the comment-outed lines in your function code snippet, you're logic is changed because when you use Path, there is added a filename [dd-MMM-yy].log to the path-string. but you don't use that addition when you use the ConfigurationManager.AppSettings("LogFilePath1") directly!
I assume that you have not used the folder path with slash (ex: #"C:\FolderName\") and that is the reason you are getting the error.
I have an error handler in my global.asax as follows;
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim ex = Server.GetLastError.GetBaseException
Dim lastErrorWrapper As HttpException = Server.GetLastError()
Dim lastError As Exception = lastErrorWrapper
If lastErrorWrapper.InnerException IsNot Nothing Then
lastError = lastErrorWrapper.InnerException
End If
My.ErrorHandler.LogError( _
"<BR/><BR/>URL: " & Request.RawUrl & _
"<BR/><BR/>STACK: " & ex.StackTrace & _
"<BR/><BR/>SOURCE: " & ex.Source & _
"<BR/><BR/>MESSAGE: " & ex.Message & _
"<BR/><BR/>TYPENAME: " & ex.GetType.ToString & _
"<BR/><BR/>INNER EXCEPTION: " & lastError.ToString & _
"<BR/><BR/>REFERRER: " & HttpContext.Current.Request.Url.AbsoluteUri & _
"<BR/><BR/>USER IP: " & Request.ServerVariables("REMOTE_ADDR") & " -- " & Request.ServerVariables("HTTP_USER_AGENT"))
End Sub
Obviously, this works great and sends me an email whenever there is an error. But, this is also true for any images that are not found in the file system. It gives me a "File does not exist." error. Is there a way to ignore logging errors for images that are not located on disk?
Cant you resolve the FileNotFoundException instead? If the exception should not occur then rather resolve the issue than suppressing it. To handle a known exception you can use the following code.
if(Server.GetLastError().GetBaseException() is System.Web.HttpException)
{
//You could check whether the
//Server.GetLastError().GetBaseException().Message contains the appropriate message
Debug.WriteLine("Suppressed FileNotFoundException");
}else
//Log an unhandled exception
var ex = Context.Error;
if (ex is HttpException)
{
var httpException = (HttpException)ex;
if (httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
return; // Do nothing 404
}
I know that this sounds very easy, or very simple, or you may search for the error code, but this is what I do - simple check if the error contains the message of dose not exist:
lastErrorWrapper.ToString().Contains("does not exist.")
I have been trying to create an error handling path for our classic asp website. I have been searching for information for 3hrs now and have not found much even here on stack overflow. So if you can point me towards a duplicate great ... I couldn't find anything although it must exist.
My plan is the following ...
Have proper error handling in the stored procedures. Any errors that occur get inserted into an error table and are also raised back up to the application.
Have "On error resume next" set on the page. Then check the connection.errors collection for errors. As well as Server.GetLastError() property.
If there are any redirect to a page to to display safe error information and insert another record into another database table to tie the page name where the error occurred to the already existing database error in the database table mentioned above for later debugging purposes.
I have created the following page to to begin testing this out. However it is not working.
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
on error resume next
cmd.CommandText = "spReturnDBException"
cmd.CommandTimeout = 30 ' 2 minutes
cmd.Execute
dim objErr
set objErr = Server.GetLastError()
if objError.ASPCode <> 0 then
response.write("ASPCode=" & objErr.ASPCode)
response.write("")
response.write("ASPDescription=" & objErr.ASPDescription)
response.write("")
response.write("Category=" & objErr.Category)
response.write("")
response.write("Column=" & objErr.Column)
response.write("")
response.write("Description=" & objErr.Description)
response.write("")
response.write("File=" & objErr.File)
response.write("")
response.write("Line=" & objErr.Line)
response.write("")
response.write("Number=" & objErr.Number)
response.write("")
response.write("Source=" & objErr.Source)
else
response.write("There's nothing wrong.")
end if
Dim objErr2
for each objErr2 in objConn.Errors
response.write("<p>")
response.write("Description: ")
response.write(objErr2.Description & "<br />")
response.write("Help context: ")
response.write(objErr2.HelpContext & "<br />")
response.write("Help file: ")
response.write(objErr2.HelpFile & "<br />")
response.write("Native error: ")
response.write(objErr2.NativeError & "<br />")
response.write("Error number: ")
response.write(objErr2.Number & "<br />")
response.write("Error source: ")
response.write(objErr2.Source & "<br />")
response.write("SQL state: ")
response.write(objErr2.SQLState & "<br />")
response.write("</p>")
next
Free(cmd)
Free(con)
In the stored procedure I simply RAISERROR( N'Lets throw an error because I want to!', 17, 0 );
The output I get every time is as follows ...
ASPCode=ASPDescription=Category=Column=-1Description=File=Line=0Number=0Source=
Description: Help context: Help file: Native error: Error number: Error source: SQL state:
Why am I not getting any error information on the conn.Errors loop?
Resolved.
I was using a different connection object for the loop that loops through the connection.Errors ... copy paste error.
However on a side note ... I found it extremely difficult to find information on how to even do what I've so far.
here's some additional resources:
some general topics:
http://social.msdn.microsoft.com/search/en-US?query=Server.GetLastError%28%29&refinement=89
a specific example:
http://support.microsoft.com/kb/224070
Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.