How to email error msg in catch
I have the code below which I now need to figure out how to not only display but also email it all to my email, this way should any user encounter a error we get to see exactly what is it.
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine + "Please contact the Service Desk to report this error.").Replace(vbNewLine, "<br />" + vbNewLine)
booInsertedRecord = False
Finally
myConnection.Close()
End Try
I Tried inserting
SmtpMail.Send开发者_如何学C(objEMail)
in a new line above "booInsertedRecord = False" and then creating a new "Dim objEMail New MailMessage()" but then realised that won't work because it's msg is defined in the catch so not to sure what steps next to take.
It's been a while since I used VB and I didn't need to use anything like this then so any assistance would be greatly appreciated.
Edit - @tzup ToString() shows
[The error was 'System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ASP.bulletinform_aspx.Upload_Click(Object source, EventArgs e) in E:\Bulletin\Bulletin\Bulletin\BulletinForm.aspx:line 415']
would of put this in a comment if I had space, line 415 is myUpdate.ExecuteNonQuery()
Use a logger like log4net and setup an SmtpAppender.
http://www.dotnetspider.com/resources/20210-Send-Exceptions-or-Error-Email-using-Log-Net.aspx
Long long time ago Jeff Atwood created an User Friendly Exception Handler. I use it since :) http://www.codinghorror.com/blog/2004/06/user-friendly-exception-handling.html
It allows to you e-mail the error, even including screenshot of the PC at the time of the exception.
Create the email object in the catch block, set the contents to the lblInformation.Text for example, and the send it.
That should work.
Create a static class for the email sending functionality, with a static function taking a string as a parameter for instance. Define this class in a util assembly, reference this assembly in your project and then call it whenever it is needed in your catch statements if you like.
Your class could be: EmailUtil.SendMail(string msg);
Then your SendMail function reads in some parameters from a config (the smtp server, login etc) and then sends the email over.
Other than that, log4net is pretty good at handling this scenario, once you configure it properly (not a very steep learning curve in my opinion)
Good luck!
EDIT
Here is an example of data validation with TryParse
string someTextVal = "3";
string someDateVal = "14.02.2011";
int i;
if (!int.TryParse(someTextVal, out i))
{
throw new Exception("Error trying to convert value=" + someTextVal + " to an int");
}
// Now i holds a validated integer
DateTime dt;
if (!DateTime.TryParse(someDateVal, out dt))
{
throw new Exception("Error trying to convert value=" + someDateVal + " to a datetime");
}
// Now dt holds a validated date
NOTE Datetime validations might require some teaks depending on how the input presents itself
LATER EDIT In case anybody needs to convert my C# code in VB (since the question was tagged with VB), here is a link to a online converter: Convert C# to VB.NET
Usually there are logging systems to do this so you do not reinvent the wheel and you do not put any logic in the catch blocks you have in your code.
You can have a look at Log4Net and also Microsoft Logging Enterprise Libraries, I personally prefer and use Log4Net, in your catch block you will simply use something like Logger.LogError(exception) and depending on how you configure it in app.config you get everything logged in database and/or eventlog and/or via email and/or text file and much, much more.
精彩评论