Unity wraps exception to the ResolutionFailedException. How to avoid? - c#

I want to know, is there the possibility to ask Unity "do not wrap any user exceptions at resolve time"?
Really, why Unity do wrappings to ResolutionFailedException? It is changing "construction service contract", IMHO the fact of objects initialization using unity should be transparent, that means if client waiting for example for IOException from "new" operator it should get it unwrapped also even object is created using Unity.
Do other IoC containers behave the same?

Because your constructors should contain no logic.
I know that's not a completely satisfying answer, but I'm not aware that you can switch off this behavior in Unity - I also do agree that it's a strange design decision...
However, if you keep your constructors simple, you will not have that problem.

Check out ResolutionFailedException.InnerException.
It is changing "construction service contract"
What contract?
IMHO the fact of objects initialization using unity should be transparent
A point of IoC containers is to make object construction less of a focus so developers can focus on adding business value.
that means if client waiting for example for IOException from "new" operator it should get it unwrapped also even object is created using Unity.
Whoa, what client is using the container that expects IOException? I think you might be misusing your IoC container.

The reason Unity wraps exceptions is all about the contract - the contract of the Resolve method.
What should an application catch when Resolve throws? Suppose you did resolve a class that you know throws IOException. So you put a catch for that exception around the resolve call.
Then the implementation changes. Or just the configuration. Now the services throw something else.
Now you've got a configuration change that will require a code change. Not good.
A second reason that with the wrapped exception the container has a place to put diagnostic information about where in the resolve process the failure occurred.

I had a similar need and found a solution here: catch all unhandled exceptions in ASP.NET Web Api
Here's what I learned when reviewing answers from the linked article:
If you only want to catch the exceptions and log them, then add an IExceptionLogger.
If you want to catch the exception and manipulate the response, then replace IExceptionHandler.
Neither solution captures ALL exceptions. I'm still using Application_Error to capture exceptions that aren't caught within my ApiController methods.

Related

Standardisation of errors within my application

So I've been trying to standardise all the error handling within my application but I've not been able to standardise all.
First I replaced the IExceptionHandler by a custom exception handler by replacing it in the WebApiConfig like so
config.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());
After this almost all exceptions were handled using a specific error standard I want to use.
Shortly after, I noticed that my OWIN exceptions weren't caught in this so I created a middleware which is inserted before any other OWIN pipelines so it can catch the OWIN exceptions and once more return in standardised format.
Now I'm stuck with a new problem. When using ASP.NET WebAPI I try to create a few REST API's. Most exceptions caused by the validations within these API's are caught and standardised by the CustomExceptionHandler but not all.
When performing a GET request with an identification, for example:
.../test/api/superhero/marvel/wolverine%20
I get a default 404 from IIS. The reason is obvious. I'm looking for a resource which doesnt exist because of the encoded space in my URL. I've made sure to catch these kind of exceptions as well if I were to perform a request which I did not register such as:
.../test/api/superhero/ma4rvel/wolverine
But for some reason I can't catch this exception caused by a rogue encoded space. I've been looking into this and the closest I've gotten to influencing this is by using the IIS web configuration customError. While this is an option to do, I simply do not want to use MVC Views for this and want this solely to rely on C# compiled code.
So here I am wondering if anyone can offer me another option.
I should clarify that this is far from a must have and is more of a nice to have. An exception caused by something like this isn't going to happen very often and I'm fine with that, but if I'm able to fix this and once more standardise my errors then I'd be happy.
Does anyone have a suggestion for this?

Why should I serialize custom exception in c#? [duplicate]

Referring to What is the correct way to make a custom .NET Exception serializable?
and Are all .NET Exceptions serializable? ...
Why should my exceptions be serializable?
Someone said "it can be considered a bug" if a custom exception defined by a third party library, is not serializable. Why?
Why are exceptions different than other classes in this regard?
Because your exceptions may need to be marshalled between different AppDomains and if they aren't (properly) serializable you will lose precious debugging information. Unlike other classes, you won't have control over whether your exception will be marshalled -- it will.
When I mean "you won't have control" I mean that classes you create generally have a finite space of existence and the existence is well known. If it's a return value and someone tries to call it in a different AppDomain (or on a different machine) they will get a fault and can just say "Don't use it that way." The caller knows they have to convert it into a type that can be serialized (by wrapping the method call). However since exceptions are bubbled up to the very top if not caught they can transcend AppDomain boundaries you didn't even know you had. Your custom application exception 20 levels deep in a different AppDomain might be the exception reported at Main() and nothing along the way is going to convert it into a serializable exception for you.
In addition to Talljoe's answer, your exceptions may be passed across Web Services as well, in this case the exception needs to be serializable/deserializable so it can be turned into XML and transmitted by the Web Service
I think that the default for all classes should be Serializable unless they contain a class that is explicitly not serializable. It's annoying to not be able to transfer a class just because some designer didn't think about it.
The same thing with "Final", all variables should be "Final" by default unless you specifically say that they are "Mutable".
Also, I'm not sure it makes sense to have a variable that is not private.
Oh well, need to design my own language.
But the answer is, you don't know how your exception will be used and they are assumed to be able to be thrown across remote calls.
Another place where objects required to be serializable is Asp.Net Session.
We store last exception in Session and not serializable exceptions needs extra translation to store their details as serializable( specifying original exception as inner doesn't help)

How ensure that some expected action is done whenever and wherever exception occurs?

I am doing some enhancements to existing code. And now I want to log one message whenever and wherever exception occurs.
I can add that message in catch/finally block but there are hundreds of catch blocks.
Can anyone suggest better approach to have the message logged whenever exceptions occurs at any part of the code in the assembly?
Second take:
A good approach is AOP with Postsharp.
I've used in many projects.
You can define an attribute that inherits from a base one of PostSharp API which permits you to intercept any method call of the one where you place your custom attribute.
If you put that attribute in any method, you'll be able to try/catch absolutely any method body, and, in the end, control exceptions and logging them.
You can achieve the same goal with Castle Dynamic Proxy, but this is a run-time solution, since you can create proxy classes with interceptors and instantiate your classes with a factory. Obviously, this is consuming more resources.
Postsharp performs IL weaving, meaning that your interceptors will be injected in your actual code in compile-time, so, you don't loose run-time performance.
Summarizing, you can create a "LogAttribute" and place it in any method you want to log or do things if an exception happens.
This is an interesting issue when you have legacy code you have to deal with.
If you REALLY do not want to change your catch blocks, then I might suggest a workaround :
One option you got is writing aLoggedExceptionInterfaceor whatever, and implement aLogEventin it, and then audit all of your code scanning for handled exception types and redefening them by adding your interface to them.
For example you would replace IOException by LoggedIOException where the latter inherits the first, implementing the LoggedExceptionInterface on top.
Of course, this might turn out to be heavier than changing catch blocks individually;The choice is yours.
For sure, you've last-chance exception handlers.
ASP.NET has it in the HttpApplication, with the Error event (most of the times in the Global ASAX if you're not using an HTTP Module).
WPF and Silverlight have then in the Application.
And Windows Forms can use the AppDomain.UnhandledException event.
Mika Jacobi is right, this is a bad answer. Sorry for that.

nicely exception handling

In our app, we use components developed by other teams. The question was how can I define a nicely way of exception handling than this
try
{
someComponent.DoStuff();
}
catch (Exception ex)
{
textLabel= ex.Message;
}
The component has no custom exception type, maybe a nicely way to do it would be to define a component specific Exception type and wrap this somehow?
I know the question is very basic, but I am interested more in the let's say how it is good to do it. If you call another component with no custom defined exception types, how do you handle any potential exceptions in an elegant way?
Ideally you would have the component development team do this for you - how else do they expect their clients to recognize and handle errors from their component? Scoping the exceptions that a component can raise is a fundamental part of good C# design.
If that's not an option, then implementing your own wrapper on top of the component to taxonomize its failure cases sounds like a good second best, and very noble of you into the bargain.
If the third-party library is poorly documented (they don't specify the exceptions that can be thrown by each method), there are tools available that can Reflect into the code and determine the possible Exceptions that may be thrown. This can get a bit daunting (there are a surprising number of exceptions that can be thrown for any given call), but it's better in principle than catching the general Exception type. Here is one commercial product that performs this type of analysis.
When you catch an error you are able to repackage it and then throw another error, at the most basic level you may just be adding more data - but, from what you've suggested, you could also replace the generic error with a custom error that, whilst it won't overcome the limitations of the response you've got from the component, would give the code further up the call stack the opportunity to respond more appropriately.
So in terms of just adding information in the most basic manner - by throwing a new exception with some additional text whilst still passing the original exception:
catch (Exception ex)
{
throw new Exception("This is more about where the exception occurred", ex);
}
Now, if you want to define your own custom component exception you change the new Exception to new ComponentSpecificException adding data as necessary to the constructor but never forgetting to set the inner exception. Exceptions also have a data collection of key, value pairs into which you can insert more information (by creating the exception, adding the data and then doing the throw).
That's all fairly generic - working forward from there, where you can't necessarily anticipate all the exceptions you have to handle you don't try - you set up logging so that you know when you've got a generic exception i.e. one that hits the final catch - and then over time add exception specific catches above the generic to provide more appropriate responses or, at the very least, package up the error into less general custom exceptions.
Not sure I've explained that very well - but the notion is that as its difficult to anticipate every possible error you want to have a strategy to develop your application in a systematic fashion as you discover new exceptions.
Assuming you want to catch every type of exception, this solution looks fine to me.
Either from your knowledge of using the component, or by using something like Reflector to analyze the compiled component, what possible exceptions can this component throw? Would providing exception handlers for these allow you to provide better feedback to you users?
The only reasonable (much less "elegant") way to handle exceptions is to log them if you can't recover from them.
Then notify the user there was a problem and offer them the chance to try again (if it's an interactive program).
If your application is exclusively for .NET developers, go ahead and show them the exception message (though Exception.ToString is better, since it includes a stack trace). Otherwise, don't display exception messages in your user interface - that's a security hole and will only confuse your users.

How would you like an API to expose error handling?

This title begs for more explanation.
Basically, I'm rolling an API that wraps a web service in a nice heirarchical model. This model exposes things in the form:
var obj = MyRemoteResource.GetForId(1234, SourceEnum.ThatSource);
ApiConsumerMethod(obj.SomeProperty); //SomeProperty is lazily loaded, and often exposes such lazily loaded properties itself
... etc ...
Where many different RemoteResources* (each with many properties exist). There's really aggresive cacheing going on, and request throttling to prevent inadvertantly DOS'ing the servers (and getting the IP of the caller banned).
I've got all this code working, but I'm not doing much in the way of error handling at the moment. Basically, if the consumer of an API provides an invalid ID, the web server is down, a connection times out, or any other of a plethora of request layer errors occur an exception just percolates up when a property is accessed.
I consider this far less than ideal.
So my question is, how should I wrap these errors up so that it is convenient for a user of this API to manage them?
Some routes I have considered:
Just wrap all exceptions in some API defined ones, and document them as thrown.
Expose a static ErrorHandler class that allows a user to register notification callbacks for specific errors; falling back to the above behavior when no registration has been made for specific errors.**
Null properties on error, and set a LastErrorCode.
Each of these approachs have strengths and weaknesses. I'd appreciate opinons on them, as well as alternatives I haven't thought of.
If it impacts the discussion at all, the platform class throwing these exceptions is WebClient. Furthermore, usage of WebClient is sufficiently abstract that it could easily be replaced with some other download scheme if needed.
*Which is to say, many different classes
**This would be... wierd. But it maps to the global nature of the failure. This is my least favorite idea thus far.
I wouldn't implement fancy error technologies (like events and stuff like this). It's not easy to judge where and how to use exceptions, but this is no reason to implements other stuff.
When you request an object by an id which doesn't exist, what do you have to tell the caller about this? If you just return null, the client knows that it doesn't exist, there is nothing more to say.
Exceptions force the caller to care about it. So they should only be used where the caller is expected to do something special. Exception can provide the information why something didn't work. But if it is an "error" the user could also ignore, an exception is not the best choice.
There are two common alternatives to exceptions.
Use return values which provide information about the result of an action. For instance, logon could return a LogonResult instead of throwing an exception.
Write two methods, one throwing an exception, and one (Try...) returning a boolean. The caller decides if it wants to ignore the "error" or not.
Personally I believe this is entirely dependent on the context of what your API end-user is trying to do. If this is the case, you should let them decide how to handle erors.
Recently when working with CSV files (very error prone) I used an API that allowed you to define the exception behaviour. You could either ignore the error, replace by some default value/action, or pass them off to an event handler.
I really liked this approach of letting the end user decide how to handle internal exceptions, because unless your API is very specific its difficult to preempt all scenarios.
I prefer to have an exception thrown at me when something bad happens. Exceptions are (for me, anyways) the common way to tell that something went wrong, and i find it more intuitive to catch, than to check a return value for null and check another property to see what went wrong..

Categories

Resources