SaveChangesException was unhandled "An error occured while processing this request." - c#

I'm using early bound classes and upon calling SaveChanges() I'm getting this generic error message which tells me nothing.
The inner exception is "an unexpected error occured"
Tracing is turned on for the server and just reposts the same error message.
Is there some way to get useful information out of this?
Thanks

Try turning customErrors on in the config file.

Try wrapping your code in:
try
{
//crm code here
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
If you catch the specific exception that's being thrown it may shed more light on the problem. Failing that, post the code / ask it in a new question and we might be able to help further.

There is a details section in the soap exception, this usually includes some additional details that help resolve your problem.
try
{
response = crm.Execute(request);
}
catch (SoapException e)
{
//Console.Write(e.Detail.InnerXml);
throw new Exception (e.Detail.InnerXml, e);
}

Related

C# catch(FileNotFoundException) and CA1031

So this code triggers CA1031.
try
{
// logic
}
catch (FileNotFoundException) // exception type
{
// handle error
}
While this one does not:
try
{
// logic
}
catch (FileNotFoundException ex) // exception var
{
// handle error
}
Because the exception type is meaningful, I don't need the ex in the first example. But it's not a a general exception type. It's not IOException or Exception. So why does it still trigger the CA1031?
So is there a difference between catch(FileNotFoundException) and catch(FileNotFoundException ex) outside the fact that I don't capture exception info?
So this code triggers CA1031
try
{
// logic
}
catch (FileNotFoundException) // exception type
{
// handle error
}
This occurs because a "general exception such as System.Exception or System.SystemException is caught in a catch statement, or a general catch clause such as catch() is used". To fix it, assign it and handle the error and or rethrow the general exception for it to be handled further up.
Upon further investigation, it seems this used to be an bug, you can see more here; it was a Roslyn issue for FxCop.
To Fix:
Just update the latest FxCop analyzers package and it should go way.
NuGet:
Install-Package Microsoft.CodeAnalysis.FxCopAnalyzers -Version 2.9.7
References:
CA1031
I have two Articles I use as basis for my Exception handling:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I also link those often when I notice Exception handling errors.
FileNotFound is clearly a exogenous Exception, so it is correct to catch it. However those articles also tell that as a general rule, to always log or expose those Exceptions. Ideally the result of Exception.ToString(). If you do not have a way to reference the caught exception, how could you do either of those two? You can only give a generic error message, but with none of the details you will actually need to debug it.
While there are many cases where you only want to expose the Exception type to the user, there is never one where you only want to log the Exception type. The linked articles mention that explicitly, but due to downvotes and comments it seems nessesary for me to repeat that.
So it is one of those cases where the argument is still going if it is a bug or a feature.
For me it certainly feels more like a feature. I would certainly call you out as potentiall issue, if I saw it in your code. It avoids you under-logging stuff. You could test if the error persist if you write throw; at the end of the catch block. This will re-throw on the exception, so a lack of being able to reference the exception in this ExceptionHandler would not be critical.

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.

How to throw a List<CustomExceptionObj> Exception at once

I have a wcf service, for which I now have made a change to keep compiling my exceptions when they occur into a list, and at the end, throw this list as an Error response. Now single errors is fine. I'm able to throw that and get the output. But throwing the list as an error is proving to be a little challenging.
-What I have tried till now: using AggregateException. I tried sniffing around for a proper implementation. So far, came up with this:
throw new AggregateException("Multiple Errors Occured", ExceptionsList)
Also,
List<CustomExceptionObject> ThrowException(List<CustomExceptionObject> ExceptionList)
{
AggregateException eggExp = new AggregateException(ExceptionList);
throw new eggExp;
}
I keep getting Unhandled Exception error using these method.
Any insight is appreciated.
UPDATE: The error message that I keep getting is -
An exception of type 'System.AggregateException' occurred in XYZ.dll but was not handled in user code.
Keep in mind that throwing a single object of my CustomExceptionObject throws a proper error response in SOAP UI. I can't seem to pull of a list of these exception.
An aggregate exception is the proper way to throw an exception that is a collection of exceptions.
throw new AggregateException("Multiple Errors Occured", ExceptionsList)
You could use this pattern:
public void DoStuff()
{
var ex = new List<Exception>();
try
{
DoSomethingThatThrowsFooException();
DoSomethingElseThatThrowsFooException();
DoSomethingThatThrowsBarException();
}
cath(FooException e)
{
ex.Add(e);
}
if (ex.Count>0)
throw new AggregateException(ex);
}
The BarException will not be caught and not be included in the AggregateException. Ultimately it could lead to an UnhandledException if not caught anywhere else.
So I overcame the issue with a hack. I'm not sure if it is the BEST way. But to get to the desirable outcome that I need, this works just fine.
STEP 1:
Create a class that has a property of List<CustomExceptionObject> type.
STEP 2:
Now when you have to throw an exception, Set this property with the incoming list,
and cast it as a FaultException type, complete with some dummy FaultReason and FaultCode.
throw new FaultException<ListOfExceptionsClass>(listofExceptions, new FaultReason("Here is the List of All exceptions"), Faultcode);
This will give a Fault Object in the response with a neat list of all exceptions occurred.

WCF/C# Unable to catch EndpointNotFoundException

I have created a WCF service and client and it all works until it comes to catching errors. Specifically I am trying to catch the EndpointNotFoundException for when the server happens not to be there for whatever reason. I have tried a simple try/catch block to catch the specific error and the communication exception it derives from, and I've tried catching just Exception. None of these succeed in catching the exception, however I do get
A first chance exception of type
'System.ServiceModel.EndpointNotFoundException'
occurred in System.ServiceModel.dll
in the output window when the client tries to open the service. Any ideas as to what I'm doing wrong?
I was able to replicate your issue and got interested (since I needed the same). I even researched a way to handle \ catch first chance exceptions but unfortunately it is not possible (for managed code) for .net framework 3.5 and below.
On my case I always get a System.ServiceModel.CommunicationObjectFaultedException whenever something gets wrong on the service or whenever I access a down service. It turns out that c#'s using statement is the cause since behind the scene, the using statement always closes the service client instance even if an exception was already encountered (it doesn't jump to catch statement directly).
What happens is that the original exception System.ServiceModel.EndpointNotFoundException will be replaced by the new exception System.ServiceModel.CommunicationObjectFaultedException whenever the using tries to close the service client instance.
The solution i've made is to not use the using statement so that whenever an exception is encountered inside the try block it will instantly throw the exception to the catch blocks.
Try to code something like:
DashboardService.DashboardServiceClient svc = new Dashboard_WPF_Test.DashboardService.DashboardServiceClient();
try
{
svc.GetChart(0);
}
catch (System.ServiceModel.EndpointNotFoundException ex)
{
//handle endpoint not found exception here
}
catch (Exception ex)
{
//general exception handler
}
finally
{
if (!svc.State.Equals(System.ServiceModel.CommunicationState.Faulted) && svc.State.Equals(System.ServiceModel.CommunicationState.Opened))
svc.Close();
}
Instead of:
try
{
using (DashboardService.DashboardServiceClient svc = new Dashboard_WPF_Test.DashboardService.DashboardServiceClient())
{
svc.GetChart(0);
}
}
catch (System.ServiceModel.EndpointNotFoundException ex)
{
//handle endpoint not found exception here (I was never able to catch this type of exception using the using statement block)
}
catch (Exception ex)
{
//general exception handler
}
And you'll be able to catch the right exception then.
Take a look at this post for details on this possible solution. The code shows use of a generate proxy but is valid on ChannelFactory and others as well.
Typical here-be-dragons pattern
using (WCFServiceClient c = new WCFServiceClient())
{
try
{
c.HelloWorld();
}
catch (Exception ex)
{
// You don't know it yet but your mellow has just been harshed.
// If you handle this exception and fall through you will still be cheerfully greeted with
// an unhandled CommunicationObjectFaultedException when 'using' tries to .Close() the client.
// If you throw or re-throw from here you will never see that exception, it is gone forever.
// buh bye.
// All you will get is an unhandled CommunicationObjectFaultedException
}
} // <-- here is where the CommunicationObjectFaultedException is thrown
Proper pattern:
using (WCFServiceClient client = new WCFServiceClient())
{
try
{
client.ThrowException();
}
catch (Exception ex)
{
// acknowledge the Faulted state and allow transition to Closed
client.Abort();
// handle the exception or rethrow, makes no nevermind to me, my
// yob is done ;-D
}
}
Or, as expressed in your question without a using statement,
WCFServiceClient c = new WCFServiceClient();
try
{
c.HelloWorld();
}
catch
{
// acknowledge the Faulted state and allow transition to Closed
c.Abort();
// handle or throw
throw;
}
finally
{
c.Close();
}
This may be a reporting issue for the debugger, rather than not actually catching the exception. this post gives some tips on resolving it, if that is the case... Why is .NET exception not caught by try/catch block?
What is a First Chance Exception?
First chance exception messages most
often do not mean there is a problem
in the code. For applications /
components which handle exceptions
gracefully, first chance exception
messages let the developer know that
an exceptional situation was
encountered and was handled.
Place a try catch block in the CompletedMethod.
An Example:
...
geocodeService.ReverseGeocodeCompleted += ReverseGeocodeCompleted(se, ev);
geocodeService.ReverseGeocodeAsync(reverseGeocodeRequest);
}
private void ReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
{
try
{
// something went wrong ...
var address = e.Result.Results[0].Address;
}
catch (Exception)
{ // Catch Exception
Debug.WriteLine("NO INTERNET CONNECTION");
}

C# Returning something from exception handle

I have the following code in a class of mine. The purpose of this class is to get the balance from a web server. Just in case something goes wrong with getting the balance. I will handle a exception. However, all this is easy to do. But I am left wondering what do I return in my catch statement.
Most of the examples I looked at just write to the console using:
Console.WriteLine(ex.Message);
That is all very well. But in a real application what do most developers do?
//Download only when the webclient is not busy.
if (!wc.IsBusy)
{
// Sleep for 1/2 second to give the server time to update the balance.
System.Threading.Thread.Sleep(500);
try
{
// Download the current balance.
wc.DownloadStringAsync(new Uri(strURL));
}
catch (WebException ex)
{
Console.Write("GetBalance(): " + ex.Message);
}
}
else
{
Console.Write("Busy please try again");
}
My function at the moment returns void. And I am just wondering what else I would return if the webclient is busy?
Many thanks for any advice,
Do not catch an exception if you cannot handle it. If you return just some value, the calling method has to check if the value is a real result or just an indicator of an exception. And now this method must decide what to do and return. And the method calling this method. And the method...
So just let the exception bubble up the stack and catch it somewhere where you can handle it. Maybe directly below the user interface and then display a message box asking if the user wants to retry or display information how to solve the problem. If you have no user interface, catch it somewhere where you can solve the problem and retry. If it is a temporary problem, retry the whole task at a reasonable level until the call succeeds.
If you want to log something, use the following pattern to log the exception an rethrow it.
try
{
DoStuff();
}
catch (Exception exception)
{
Log(exception.ToString());
throw;
}
Note that it is throw; and not throw exception;. If you do the later, you lose the original stack trace. If you can infer more details about the cause of the exception, you should wrap the caught exception into a more meaningful exception with additional information.
try
{
DoStuff();
}
catch (SpecificMeaninglessException exception)
{
Log(exception.ToString());
throw new MeaningfulException("Details about the error.", exception);
}
catch (Exception exception)
{
Log(exception.ToString());
throw;
}
You should use ex.ToString() method
Exception.Message
contains a simple description of the exception (e.g. "Object reference not set...").
Exception.ToString()
contains a description of the exception along with a complete stack trace.
Exception Handling Best Practices in .NET
You could re-run the method if the client is busy but wait a certain time before retries? Potentially with a failure after x retries.
If instead you wish to move on and simply log the problem, your catch statement could log the exception to a file-based log, event viewer, submit to a database, raise an alert (email, sms etc.) if it is necessary.
Depends on the severity of the exception.
I would suggest looking into The Exception Block from Patterns & Practices
If you're only interested in viewing the exception you should re throw the exception so who-ever is planning on handling it will still get it.
You certainly don't want to mask an unhandled exception. Let that bubble up through the stack. But if you are asking what to return if the web client is just busy, how about
returning either a random interval or some meaningful interval that the function caller should wait before attempting to download the balance again? A random number could distribute load or otherwise mitigate a collision problem. A more meaningful interval could be sent back based on the the current state of the server.

Categories