Tuesday, April 11, 2017

How to catch an error and send via email and log to the server (aka simple text file not event log). (VB.NET)

Catch ex As Exception
            'Log to exception table
            Dim strError As String
            strError = Now().ToString() & "Error: (Class=PromoCode;Method=IsEmailRequired)" &
                       ";" & vbCrLf & "PromoId = " & promoCodeId &
                       ";" & vbCrLf & vbCrLf & "Exception " & ex.ToString()

            MiscFunctions.SendExceptionEmail(strError)
            MiscFunctions.WriteLogRecord(strError)

            myPromoCode = Nothing
            Return myPromoCode
        End Try



 '---------------------------------------------------------------------------
    'Description: Email Exception Error
    '---------------------------------------------------------------------------
    Public Shared Sub SendExceptionEmail(ByVal errorException As String)

        Dim myMail As New MailMessage()

        myMail.From = New MailAddress("error@domain.com")
        myMail.Subject = ConfigurationManager.AppSettings("CoreHTTPPath") & " error exception"

        'Create an email from the email addresses in the app.config file
        Dim emailTo As String = System.Configuration.ConfigurationManager.AppSettings("AdminEmails").ToString()
        Dim strEmailArray() As String

        strEmailArray = Split(emailTo, ";")

        For Each email As String In strEmailArray
            myMail.[To].Add(email)
        Next


        Dim sb As New StringBuilder()
        sb.Append("www.domain.com error exception: " & vbCrLf & vbCrLf)

        sb.Append(errorException)


        Dim strBody As String = sb.ToString()
        myMail.Body = strBody

        myMail.IsBodyHtml = False

        Dim smtp As New SmtpClient()


        Try
            smtp.Send(myMail)
            myMail = Nothing
        Catch ex As System.Exception
            WriteLogRecord(Now().ToString() & " Error: (Function Sending errorException) " & ex.ToString)
        End Try

    End Sub

    Public Shared Sub WriteLogRecord(ByVal strErroMsg As String)

        Dim objWrite As IO.StreamWriter
        Dim strDateTime As String = Now().ToString()
        strDateTime = Replace(strDateTime, "/", "-")
        strDateTime = Replace(strDateTime, ":", "")
        objWrite = IO.File.AppendText(System.Configuration.ConfigurationManager.AppSettings("EmailErrorLogs") & "/EmailErrorLog.log")
        objWrite.WriteLine(strErroMsg)
        objWrite.Close()

    End Sub





Post a Comment