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?
Related
This is the weirdest thing that has ever happened to me so please hear me out.
Symbols are getting loaded properly. So thats not an issue.
API is working and the data is valid.
I've 2 controllers in the same project. One controller's breakpoint is hit when I make a GET request. But the second controller's breakpoint isn't getting hit. However it does return results correctly.
I'm putting a breakpoint at the constructor level (and have tried everywhere else) but not sure what is going wrong.
The code is pretty normal C# MVC web api.
Does anyone know what might cause this behavior?
One trick I like to use is to use Exceptions. First you change some public method in your "bad" Controller to just unconditionally throw some dummy Exception. Then call that method from whatever uses you WebAPI and make sure the Exception is actually thrown. Sometimes something get cached and code is not actually re-compiled or something.
Then attach your debugger and see if it catches the Exception. You might be attaching to a wrong process.
Next modify code to throw and catch that Exception and just log it. The trick here is that VS Debugger has an option to stop even on caught aka "user-handled" exceptions: see configuration here for VS up to 2013 and here for VS 2015+. Then you can see if symbols actualy matches the code.
I had similar issue - try this site out that might help
breakpoint issue
Meanwhile try to force a breakpoint
System.Diagnostics.Debugger.Break();
Does the controller, which works but doesn't hit the breakpoint, output cache whatever it is that is being generated? If it is, the data will be returned by whatever is caching it, and the controller won't be instantiated.
It's not clear whether you are using MVC or WebAPI controllers or what you are returning. However if it's MVC you could look for the [OutputCache()] attribute. You could also keep an eye out for other cache related headers which might be getting added.
Depending on the caching strategy you might be able to circumvent it by adding a random query string value so that it has to create a new cache key. For example:
http://example.com/some/path/1234?cow=moo
try this instead
1.Go to project "Build settings"
2.Search Debug
3.Under Apple Clang - Code Generation check "Optimization Level"
4.Set Debug to None [-OO]
I had the same problem just a moment ago before writing this down... Try going to properties of you webapi and compare if the project url found in the web section is the same as the url specified in your website's webconfig file. As for my problem, the website was pointing to the webapi properly which allows any code changes in the webapi to be read however, the debugger is pointed in the wrong place thus it cannot read any breakpoints you place.
I have a WebAPI application where we often drop various custom dlls into the bin folder for additional functionality. Sometimes the custom dlls reference other custom dlls, which reference other custom dlls... it can be a bit of a nightmare.
Occasionally I will either miss something, or something goes screwy, and I get the infamous YSOD (Yellow Screen Of Death) upon starting the API.
The YSOD will often display the name of the troublemaker assembly, which helps a little, but what I really want to know is the dll(s) that I'm missing. And I know that I can get this information from the LoaderExceptions property if only I could catch and handle the exception!!
I've got a lot of exception handling at a few different levels, including a global exception handler, but after trying quite a few different things, and finding this (so far) unanswered question, I'm getting a nasty suspicion that this exception is occurring in IIS outside of my app, and I have no control over it.
If that IS the case, is there a way I can examine the exception in IIS? Otherwise why would it suggest retrieving the LoaderExceptions?
If NOT the case, how/where/when can I catch and handle this type of exception?
EDIT:
From David's comment below, I have also tried hooking to AppDomain.AssemblyResolve, AppDomain.UnhandledException, and AppDomain.FirstChanceException events, and none of these are catching the yellow screen exception either...
Up until recently we used custom exceptions with an inbuilt errorcode to allow us to communicate errors or problems we don't like around our systems.
However, I was shown a different method where you have a publicly exposed collection of errors on each class that you populate if there was a problem. The calling method then calls myObject.IsValid (which sees if the error collection has any entries) to check if the call was successful. If it wasn't then you can iterate through the error collection to see what went wrong. As far as I understand this is how MVC works with the ModelState.
The claim was this was the more efficient approach to error communication as there is an overhead to throwing exceptions.
Is this claim true? Is there a third option that is even better than the above? What is the correct way to communicate errors and problems around a .NET application?
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.
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..