Encountered a strange problem with this event, event wrapper and handler:
public delegate void StatusUpdateHandler(string message, Exception exc, SeverityLevel severity);
public event StatusUpdateHandler StatusUpdate;
private void FireStatusUpdate(string message)
{
if (this.StatusUpdate != null)
this.StatusUpdate(message, null, SeverityLevel.None);
}
void scanDocProcessor_StatusUpdate(string message, Exception exc, SeverityLevel severity)
{
try
{
if (exc != null)
{
if (severity >= setSevLevel)
this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Emergency, "OCR Submission Processor Status Update", true);
else
this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Error, "OCR Submission Processor Status Update", false);
}
else if (severity >= setSevLevel)
{
this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", true, true);
}
else
this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", false);
}
catch (Exception)
{
EventLog.WriteEntry("Russia OCR Submission Processor", "Could not log status update event: " + exc.ToString(), EventLogEntryType.Information);
}
}
For a period of a few minutes, the _logger stopped logging messages and instead I received these messages in the event log:
Could not log status update event: System.NullReferenceException: Object reference not set to an instance of an object.
at ScannedService.scanDocProcessor_StatusUpdate(String message, Exception exc, SeverityLevel severity)
at ScannedService.Processor.FireStatusUpdate(String message)
at ScannedService.Processor.ProcessQueue(Object Object)
I'm confused how the Event log could get such a stack trace when it should be writing exc.ToString(). I looked at the IL for the scanDocProcessor_StatusUpdate method is not initializing an Exception object. Beyond that I don't know how a nullreferenceexception is getting thrown. When the Log method does catch an exception it swallows it or re-throws it with "throw;". The message parameter is never null and SeverityLevel is an enumeration.
You are throwing an exception in one of the else conditions where ecx is null. In the catch block, you are assuming that ecx is not null, which generates another exception that hides your original one.
You can make your log statement null-safe with the following:
EventLog.WriteEntry("Russia OCR Submission Processor",
String.Format("Could not log status update event: {0}", exc), EventLogEntryType.Information);
Related
I can't see CreateErrorResponse message in exception. I am passing message "Invalid Parameters" to ThrowResponseException method but i can't read it in exception.
e.Response.RequestMessage gives default detail message but i only need to read "Invalid Parameters".
try
{
If (!ValidString)
{ ThrowResponseException(HttpStatusCode.BadRequest, "Invalid Parameters");}
}
catch (HttpResponseException e)
{
msg = " Status Code: " + e.Response.StatusCode.ToString();
}
private void ThrowResponseException(HttpStatusCode statusCode, string message)
{
var errorResponse = Request.CreateErrorResponse(statusCode,message);
throw new HttpResponseException(errorResponse);
}
I found something similar where they wrap the message in a new exception and pass that exception into the create response. Then they can pull out the text of the error message.
How can I retrieve the exception message from Request.CreateErrorResponse?
return Request.CreateResponse(statusCode, new Exception(message));
I have a project (SharePoint-Addin), that throws a CryptographicException from time to time on my customers machine. This Exception happens before even entering any Controller-Action.
I want to catch that error, analyze it and react accordingly. (Currently my guess would be this is some kind of token expiration, so I want to simply show the login-page if this happens)
I got the following code:
protected void Application_Error(object sender, EventArgs e)
{
_log.Error("ExceptionError occured ");
Exception exception = Server.GetLastError();
if (exception!=null)
{
_log.Error(exception);
if (exception is CryptographicException)
{
Response.Redirect(loginPage, true);
}
}
}
This will (hopefully) work, but this question is not about the code, but about how to force a CryptographicException.
Can I add an "evil header" to a request so this will fire?
Look here at MSDN:
https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptographicexception(v=vs.110).aspx
private void StringConstructor()
{
// Construct a CryptographicException using a custom error message.
string errorMessage = ("Unexpected Operation exception.");
CryptographicException cryptographicException =
new CryptographicException(errorMessage);
Console.WriteLine("Created a CryptographicException with the " +
"following error message: " + errorMessage);
}
or just
throw new CryptographicException(errorMessage);
I have following error handler in my console application
Main Procedure:
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(ErrorHandler);
Handler Procedure:
static void ErrorHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
... Loging Error ...
//Environment.Exit(?);
}
And the problem is that error is logged but after that application failed and windows popup (application is not responding) is showed.
So i want to add Environment.Exit() to prevent that behavior, but how to specify the exitCode from the exception ? I dont want to set Exit(0) (which means everything is okay) because i also want see the error (only information that some error happened, exception is already logged) in the scheduler application which trigger this script.
Thank you
Most programmers simply use Environment.Exit(1). Almost always works just fine. But that is not technically correct, if a program dies on an exception then its exit code is normally the same as the underlying exception error code. The event handler ought not change that behavior.
Doing it right is a mouthful:
Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(e));
There's a FUD factor here, you can't completely trust a library with custom exception objects that don't set an error code. Still okay, the fallback is E_FAIL.
Can you use the Exception.HResult?
Consider the following code:
class Program
{
static int Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; ;
if (args.Any() && args[0] == "/t")
{
Console.WriteLine("I am going to throw an exception");
throw new ApplicationException("This is an exception");
}
else
{
Console.WriteLine("I am going to exit");
//Environment.Exit(0);
return 0;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("An unexpected error has occurred");
Exception ex = (Exception)e.ExceptionObject;
Environment.Exit(ex.HResult);
}
}
Then execute this from a batch file twice - once with the /t parameter and the other without:
#echo off
cls
echo Running Console Application with no error
ConsoleApplication2.exe
echo %errorlevel%
echo Running Console Application with error
ConsoleApplication2.exe /t
echo %errorlevel%
pause
In the first run you exit with 0. I've made Main return an int and just return 0 for successful execution - you can do Environment.Exit(0) here.
With the second run that throws an ApplicationException, the UnhandledException is handled, then Environment.Exit(ex.HResult) is called.
I think the HResult is tied in to specific exceptions as per MSDN. However, you may want different exit codes depending on what caused the exception. In this case you can throw custom exceptions then have some cafuffled logic in the UnhandledException handler:
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("An unexpected error has occurred");
Exception ex = (Exception)e.ExceptionObject;
if (ex is MyException)
{
Environment.Exit(10009); // my own exit codes
}
Environment.Exit(ex.HResult);
}
}
class MyException : Exception
{
}
But would you really care why it failed in the console? If you get an unhandled exception then it failed. You can have lots of possible failure points. What are you really going to do with the error code? You have logged the exception out. That provides the vital information.
I'm using TweetSharp to find the followers for a user.
Here is the code:
public static void FindFollowersForUser(TwitterUserModel twitterUser)
{
try
{
var followers = service.ListFollowersOf(twitterUser.TwitterName, -1);
if (followers == null) return;
while (followers.NextCursor != null)
{
var foundFollowers = service.ListFollowersOf(twitterUser.TwitterName, (long)followers.NextCursor);
if (foundFollowers == null) continue;
Debug.WriteLine("Followers found for: " + twitterUser.TwitterName);
foreach (var follower in foundFollowers)
{
twitterUser.Followers.Add(follower.ScreenName);
}
}
}
catch (WebException e)
{
throw e;
}
}
I've tried wrapping the code in a try/catch, to catch the WebException error being fired and review it's InnerException, but the catch is never entered despite the error message being shown in the output window (View -> Output) in Visual Studio.
How can I see the inner exception of this breaking bug? This is the first time I've seen the debugger not firing the catch when an exception is fired.
I assume when you say "First chance exception" you mean the message that is output to the Debug console? That message is output whenever an exception is thrown. The exception may be caught by code and handled and not allowed to propagate up the stack. TweetSharp may be catching this exception within its code and handling in some way so it never reaches your catch block
This is normal and only the debugger displays this message. If this is a problem for you in some way (other than the message displaying in the Output window), please provide more detail.
I was looking something else, really, but this cought my eye. If you are planning to rethrow exception then you want to replace this
catch (WebException e) { throw e; }
with this so you won't mess up the stacktrace.
catch (WebException e) { throw; }
Is there any way to get sent error from the smtp to check if the mail is sent successfully?
var smtpClient = new SmtpClient("SmtpServer");
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtpClient.SendAsync(mail, userId);
The errors I am looking for are: mail can't be deliver because the mail address not exists, mail box full etc...
Regards,
Meir.
I am not sure what you are trying to achieve but this will helps you.
I assume you're already aware of the DeriveryNotificationOptions property on System.Net.Mail.MailMessage. The only tricky part to using that property is that its enum type represents a bitfield, so you should set it to the sum of the options you want to apply.
For example, if you want delivery notification on delay, failure, or success, you should set the property to
DeliveryNotificationOptions.Delay + DeliveryNotificationOptions.OnFailure + DeliveryNotificationOptions.OnSuccess
Or
this is one method to capture the failure report or any error when the mail has not been sent (failure report)
// Change your Try-Catch to call the new method named 'CheckExceptionAndResend'
// Error handling for sending message
try
{
smtpClient.Send(message);
// Exception contains information on each failed receipient
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
// Call method that will analyze exception and attempt to re-send the email
CheckExceptionAndResend(recExc, smtpClient, message);
}
catch (System.Net.Mail.SmtpException smtpExc)
{
// Log error to event log using StatusCode information in
// smtpExc.StatusCode
MsgBox((smtpExc.StatusCode.ToString + " ==>Procedure SmtpException"));
}
catch (Exception Exc)
{
// Log error to event log using StatusCode information in
// smtpExc.StatusCode
MsgBox((Exc.Message + " ==>Procedure Exception"));
}
private void CheckExceptionAndResend(System.Net.Mail.SmtpFailedRecipientsException exObj, System.Net.Mail.SmtpClient smtpClient, MailMessage emailMessage)
{
try
{
for (int recipient = 0; (recipient <= (exObj.InnerExceptions.Length - 1)); recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
// Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = exObj.InnerExceptions(recipient).StatusCode;
if (((statusCode == Net.Mail.SmtpStatusCode.MailboxBusy)
|| (statusCode == Net.Mail.SmtpStatusCode.MailboxUnavailable)))
{
// Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000);
smtpClient.Send(emailMessage);
}
else
{
// Log error to event log.
// recExc.InnerExceptions(recipient).StatusCode or use statusCode
}
}
MsgBox((exObj.Message + " ==>Procedure SmtpFailedRecipientsException"));
}
catch (Exception ex)
{
// At this point we have an non recoverable issue:
// NOTE: At this point we do not want to re-throw the exception because this method
// was called from a 'Catch' block and we do not want a hard error to display to the client.
// Options: log error, report issue to client via msgbox, etc. This is up to you.
// To display issue as you have before:
MsgBox((exObj.Message + " ==>Email was not sent"));
}
}
Such kind of errors have a asnychronous nature. When sending mail you talk to the local smtp server of your provider. That server afterwards starts to deliver the mail to the target mail system.
So the SmtpClient class can only show you errors occuring while talking to your local smtp server.
Typically when an error like "unknown user" occures on the target system, it will send an email with the failure message to the originator email address.
This post is helpful to me.
By the way if you're using .net 4.0 this one will be the changes on the above code. Sorry for my first post i don't know why it appears that way.
Here's the code:
private void CheckExceptionAndResend(System.Net.Mail.SmtpFailedRecipientsException exObj, System.Net.Mail.SmtpClient smtpClient, MailMessage emailMessage)
{
try
{
for (int recipient = 0; (recipient <= (exObj.InnerExceptions.Length - 1)); recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
// Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
//for .net 4.0
//statusCode = exObj.InnerExceptions(recipient).StatusCode;
statusCode = exObj.StatusCode;
//if (((statusCode == Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == Net.Mail.SmtpStatusCode.MailboxUnavailable)))
//for .net 4.0
if (((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy)
|| (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable)))
{
// Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000);
smtpClient.Send(emailMessage);
}
else
{
// Log error to event log.
// recExc.InnerExceptions(recipient).StatusCode or use statusCode
}
}
//MsgBox((exObj.Message + " ==>Procedure SmtpFailedRecipientsException"));
}
catch (Exception ex)
{
// At this point we have an non recoverable issue:
// NOTE: At this point we do not want to re-throw the exception because this method
// was called from a 'Catch' block and we do not want a hard error to display to the client.
// Options: log error, report issue to client via msgbox, etc. This is up to you.
// To display issue as you have before:
// MsgBox((exObj.Message + " ==>Email was not sent"));
}
}