Is is possible to strip a call stack from an exception string? - c#

Exceptions are used throughout the component I'm working in for API error handling:
catch (Exception ex)
{
// ex.ToString() below may be something like "database is locked"
string error = string.Format(
"Error when trying to create a playlist: {0}", ex.ToString());
throw new Exception(error);
}
Basically a lower-level component will throw an Exception with detailed specifics of the error, and this will be caught at a higher-level with a more generic, user-friendly error message.
When my client application processes this application, it calls ex.ToString() to get the complete error string, but this also includes the call stack.
Error: exceptions.RuntimeError: Error when trying to create a playlist:
System.Exception: database is locked
at <very large call stack here>
Is there an easy way to prevent the last section (i.e. at <very large call stack here>) from appearing in the error message, without having the parse the string? This is being returned to the user and I want the error to be user-focused not application-focused.

Try using Exception.Message instead of Exception.ToString:
string message = string.Format(
"Error when trying to create a playlist: {0}", ex.Message);
throw new YourException(message, ex);

Related

How do I catch Revit errors in Revit API?

I'm trying to catch an error displayed in Revit to perform some handle operations. Error is due to the connection of points as shown in the image below.
Error image
This is what I have tested with so far.
try
{
var pipe = Pipe.Create(doc, firstPipeType.Id, level.Id, startCon,
pathXyz[0]);
}
catch (Autodesk.Revit.Exceptions.InvalidOperationException e)
{
message = e.Message;
return Result. Failed;
}
Based on the documentation, I am trying to catch and handle the following exception.
"Autodesk.Revit.Exceptions.InvalidOperationException: Thrown when the new pipe fails to connect with the connector."
The error message is different from the exception. The instructions on how to handle the error message are provided by The Building Coder in the topic group on Detecting and Handling Dialogues and Failures.

Give user option to send error-report on uncaught exception

I've developed an application used by a third-party company.
Since I'm a horrible coder the application does still have some bugs which causes it to crash (unhandled nullpointerexception for example).
It's a Windows-forms application running on .NET 4.5 and now they are just getting the classic "An unhandled exception caused the app to terminate, press details for more info".
Trying to convince them that pressing "Details" and sending the stack-trace to me is really useful but they all seem reluctant.
Would it be possible to automate this behaviour, like show them a custom global "Exception catcher" where they can just press a button to send it to me by E-mail.
Inbefore "Global exception handling is bad" and "Why does your application throw nullpointerexceptions, you are a bad coder etc."
BR Tomas Anyuru
I guess the exceptions you get are unhandled.
Because of this, you will have to use the Application.ThreadException event to handle them. Because there is no .NET automatic mail sending and message display, you will have to implement your own inside this event.
Please have a look of an answer I wrote to have some examples of Exception catching strategies.
wrap your whole main() function in try-catch statement.
this way any un-handled exception will roll back and will be catched in your catch block:
static void main()
{
try
{
// the application code...
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show(
"Some error occured, please click ok to send it to the develpoer");
if (result = OK)
email(ex); // this is your function to send the email.
// useful information is also in ex.message
// here program will exit without error!
}
}
you can use log 4 net it is open source logging tools, use a lot by Java developer, and this version is specially for .Net http://logging.apache.org/log4net/
In addition to #Shamim code, you can wrap your main function in try, catch block, since the catch block here will track down the exception occurred inside any function called in the try block.
Shooting a mail inside catch block sometime throws and exception about Thread abort, so finally would be the right place to do so :
catch (Exception err)
{
mailBody = "Error: " + Convert.ToString(err.Message) + "<br /> Source: " + Convert.ToString(err.Source);
//Can display some message to user in an Literal Control from here.
}
finally
{
if (!string.IsNullOrEmpty(mailBody))
{
mailObject.To.Add(mailTo);
mailObject.CC.Add(mailCc);
mailObject.Body = mailBody;
MailService(mailObject);
}
}
MailService is a method to send mail which accept a MailObject as parameter.

Do I need to catch each individual exception type if I'm going to perform the same action?

Simply put, I don't expect this application to receive too many errors since it's a fairly controlled environment and the users are other developers.
Having said that, errors do happen sooner or later and I simply just want to keep a log of them and alert the user. I've got this method that tries to validate the information as best as it can, then it tries to copy a file from A to B.
try
{
File.Copy(source, destination, true);
return String.Empty;
}
catch (Exception ex)
{
logOp.AddLog(ex);
return string.Format("ERROR: {0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace);
}
The method returns an empty string if it was successful, and if not it logs the exception and returns it to the calling method for presentation.
Do I need to catch each individual Exception type that File.Copy can throw if I want the most detailed Message / Stack trace, or will just catching Exception work? I tried hardcoding it to throw new instances of the various Exceptions and it seems OK but I wasn't sure if there was some programming principle I was missing/violating
Since all you're doing in exception handler is logging, then I'd say no, just take the Exception and log the message.
Catching individual exceptions would be useful if you attempted to recover from the error.
I would keep it as is and just catch the base class Exception.
Logging the ex.ToString() like you implicitly do in logOp.AddLog(ex) should write the actual type of the exception (which could be one of these that File.Copy method can throw in the Exceptions section here )
Based on that link, the name of the actual exception should be informative enough since you are not attempting to recover from the exceptions, just logging them.

How to print the exception in Windows Phone?

I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. So here is what I am doing:
try
{
//The code which I want to handle for exception
}
catch (Exception e)
{
ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
}
where ErrorStatus is my TextBlock.
However, the only line in my catch block is giving me an exception during the runtime. The exception is:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Am I doing something wrong syntactically? I am new to C# programming as well as Windows Phone programming.
Edit:
More details of the exception:
System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException:
You need to show your message from the UI thread: web calls always callback on a background worker thread. So, you need to call the Dispatcher to get this to run on the UI thread.
Also you can just use Exception.ToString() to show the message content as a string. This has the advantage of also showing any nested exceptions inside the one you're handling.
As a temporary measure try:
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
}
}
More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code.
This is the best way to print out your exception message so that you may know where the problem is:
try{}
catch(Exception ex)
{
await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}

SoapServerException.HandleException()

I'm confused about how this method is actually handling the exception that is passed to it, it doesn't appear to do anything extra.
I have it in a segment of my code as it was the standard being used in one of the examples I looked at the other day but I've since found that it seems to eat my Exception messages so I am left with the generic SoapServerException with no InnerException.
// "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
catch (Exception ex)
{
throw SoapServerException.HandleException(exception);
}
// "Server was unable to process request. ---> Error in MyService.asmx --->
// Could not load file or assembly 'That.Assembly.I.Forgot' or one of its dependencies."
catch (Exception ex)
{
throw new Exception("Error in MyService.asmx", ex);
}
Is there a reason I should throw SoapServerException.HandleException() instead of my own more descriptive exception?
Per: http://msdn.microsoft.com/en-us/library/gg552614(v=office.14).aspx#bestpractice_infodisc
SoapServerException.HandleException() is intended to reduce the details returned to the user for security reasons. So this behavior is intentional.
The documentation for this method: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.soapserver.soapserverexception.handleexception.aspx
doesn't really explain what this method does as at all, which is unfortunate. If you deliberately want to provide more details to the user, then you should use your own exception. But be careful about providing such details. It may not be a good idea for security reasons. It really depends on how much you trust/know the party you are sending the error to.
-Dave

Categories