gibbo1715

Hi All

Could I ask your thoughts on the following please, I am looking to make a generic error handling function which i can just call, was interested in your thoughts on how to improve the attached

cheers

Gibbo

Code Snippet

Function ErrorLog(strErrDesc As String, lngErrNum As Long, strWhereFrom As String) As Boolean

On Error GoTo Err_ErrorLog

Dim strMsg As String


ErrorLog = True

strMsg = strMsg & "There has been an error in the application." & vbCrLf & vbCrLf
strMsg = strMsg & "Error Number: " & lngErrNum & vbCrLf
strMsg = strMsg & "Error Description: " & strErrDesc & vbCrLf
strMsg = strMsg & "Error Location: " & strWhereFrom & vbCrLf

strMsg = strMsg & "Please note the above information when contacting Me" & vbCrLf & vbCrLf
strMsg = strMsg & "Thanks Gibbo"

MsgBox strMsg, vbInformation, "Error Log."

Exit_ErrorLog:
Exit Function

Err_ErrorLog:

ErrorLog = False

MsgBox Err.Description, , "Error detected."
Resume Exit_ErrorLog

End Function


'call as follows
'Call ErrorLog(Err.Description, Err.Number, Me.Name)




Re: Visual Basic Express Edition Generic Error Handling Code

jo0ls

You could use a resource for the error message:

Go to the project properties and click resources.

Add a String resource called "GenericErrorMessage". For the message text, put this all on one line:

There has been an error in the application.{0}{0}Error Number: {1}{0}Error Description:{2}{0}Error Location: {3}{0}Please note the above information when contacting me.{0}{0}Thanks Gibbo

We can then use string.format to replace the {0} with a newline, and {1}, {2}, {3} with the variables...

Sub ErrorLog(ByVal Description As String, ByVal ErrorNumber As Integer, _
ByVal WhereFrom As String)

Dim message As String = String.Format(My.Resources.GenericErrorMessage, _
Environment.NewLine, _
ErrorNumber, Description, WhereFrom)

MessageBox.Show(message, "Error Log", MessageBoxButtons.OK, _
MessageBoxIcon.Information)

End Function

Try...Catch is the standard practice now. It's a big topic. On Error remains for backwards compatibility. You need to learn the new error handling practices and banish On Error from your code.

Using Environment.NewLine prevents problems in the unlikely event that you port code to a non windows platform.

Using MessageBox is a bit more efficient, and C# coders will understand your code more easily.

Using lots of concatenation creates a seperate string object for every part, using a big string is more efficient.

Resources help to tidy things up, you can also provide different language versions of the resources, and have all your messages pop up in the correct language for the users locale.