I am implementing a error logger for a web shop and just logging a NullReferenceException in a specific class is only useful to a certain level. I am not really interested in how to prevent the exception, as I am aware of that, but sometimes it still happens thus the error logger.
Then the question is: How do I find the source of a System.NullReferenceException inside all the exception information.
Make sure you log the full stack trace. Assuming you've got debug information turned on (no reason not to for a web app...) you should be able to get to the line which caused the problem.
Of course, that won't always give you all the information you need, if you've got:
if (foo.Bar.Baz && person.Address.Road.Length)
in a single line... but it's the best starting point you'll get.
Additionally, adding argument validation to methods can make it a lot simpler to pin down what's wrong. Personally I'm a fan of helper methods for this. For example, in Noda Time we have Preconditions, so I can just call:
Preconditions.CheckNotNull(foo, "foo");
(which also returns the value of foo, which is handy in constructors which are copying arguments into fields).
The earlier you can detect the unexpectedly-null reference, the better.
If I understand the question correctly, in Visual Studio, go to Debug > Exceptions, and check all options to throw exceptions. This will allow you to see everything that is being thrown while debugging. You can possibly use the contents of InnerException to determine what the root location of the error is being caused.
Related
I am trying to add more specific error handling to my c# app, but I am finding it hard to track down what exceptions are thrown by classes and method. Is there a way through visual studio 2010 to find this info, or maybe an exception list?
Just find the class/method you are interested in on MSDN.
For example, look at this page for the Dictionary.Remove Method. If the method throws an Exception (like this one), you can get the information for the Exceptions section of the page.
If you are talking about .Net framework methods, they are documented in the hover over help. You will see Exceptions: . Or you can see it in the object browser Ctrl+W, J as well. Or press F1 over a function to go to MSDN help, where they are documented in detail.
If you're allowing the exceptions to be thrown, you should be able to see the exception details in the Event Viewer in Administrative Tools.
You can find specific uses of a particular exception, but there is no complete listing of all exceptions any method might throw.
Consider the following method:
public void SomeMethod()
{
SomeObject x = null;
x.SomeMethod(); // NullReferenceException
File.Open("SomePath", FileMode.CreateNew); // Any number of File Exceptions potentially
throw new CustomException();
};
How would a code analyzer be able to determine which potential exceptions there were?
If you're looking for information on a specific class, I'd check the documentation for it.
So I got the dreaded "yellow screen of death"(? that's what the .NET guys called it) with the error message:
[NullReferenceException: Object reference not set to an instance of an object.]
OK, that's fine, I can understand that, but the error references a line of code which reads:
<namespace1>.<namespace2>.XMLDohickey responseXML =
new <namespace1>.<namespace2>.XMLDohickey();
(names obscured to protect the innocent (: ).
I can easily see how the line after, Session[<value>].ToString();, could cause this error, but I don't understand how the error could be caused by the line it claims to be caused by.
So, is it that C# is telling me the wrong line number, or can a namespace actually be null?
As a side note -- this seems to work fine locally, on my company's DEV and QA servers, but it seems like it failed on our client's QA server...
EDIT
So... here's the deal.
Apparently, when .NET crashes, sometimes it returns the last successful line called instead of the line which actually held the error. In this case, the Session[<value>] was null (Why? No idea. that "Should never happen").
A namespace can never be null, it will never generate any runtime errors of any kind (in the way you are describing it). So your null reference is probably in Session[key].ToString(), or the constructor of XMLDoHickey. I would consider checking if the value in the session state exists before calling a method on it.
Are you sure the exception doesn't come from inside the XMLDohickey constructor?
You need to force a recompilation and probably also clear the temporary internet files.
THere are often mismatches in the line numbers and the actual instruction causing the exception when source and binaries get out of sync and this must be the case here since namespaces surely dont cause null reference exceptions :)
I'm working on a logging program, and I'd like to avoid processing the same Exception object repeatedly when it is being logged repeatedly because it is percolating up through a nested call structure. So I'd like to be able to format the Exception object once, and give the formatted version a unique "exception number" and then tag the Exception object somehow so I can recognize it if it turns up again in a later log call.
The idea I've come up with is to misuse the HelpLink field of the Exception object. I'll set it to contain a string version of my "exception number". Then I can recognize the Exception object if it shows up again momentarily in another log call.
But is this maybe a bad idea? Are there any gotchas involved that I haven't thought of? If so, does anyone have a better idea?
EDIT:
To explain the situation a bit more, this logger will only be used on my own programs.
Instead of 'abusing' HelpLink property, you could use Data property to add extra information to the Exception. It contains key/value pairs that provide additional user-defined information about the exception.
While I agree with TheVillageIdiot, I would point out that more generally speaking, if you want to change the behavior of Exception, then you should create your own Exception class that add's additional pertinent information. That's why we use inheritance and polymorphism, after all. :)
Definitely it is not okay to use Exception.HelpLink because logger should be concerned with logging the exception information only in given format or any default format. If same exception is coming again and again it is problem of the executing assembly or program not the logger.
Better still you can explore the options of using log4net for logging and custom reporting interface to format/group exception from the log files or database tables created/updated by log4.net
No it is not acceptable to misuse the HelpLink. As #Greebo mentioned if you need additional properties you could create your own exception classes. An alternative might be to use the Data property that is part of the System.Exception class.
Question: Are your exception handlers doing any handling other than logging?
If not then most likely your don't need the handlers. Just let the exception (using a finally block for cleanup) bubble up the call stack and handle it at the outmost layer. If your handlers are handling the exception then I'm not sure why you would have the same exception further up the stack. I would think it would be more likely that you would create a new exception setting the inner exception to the one that was handled.
Your code should not be catching and logging the exception at every level. There's no reason that your code should ever be seeing the same exception twice. This sounds very much like you are using "catch every exception", which is a major anti-pattern.
In my ASP.NET MVC application, I do not want to report all exception messages to the user. But there are certain types of exceptions that I'd like to report to the user, so I created an action filter to decide if it's this particular type of exception, and if so then display the exception's message, otherwise display a generic message. So I created a custom exception called ClientException.
My filter looks something like this:
if (filterContext.Exception is ClientException)
message = filterContext.Exception.Message.Replace("\r", " ").Replace("\n", " ");
else
message = "An error occured while attemting to perform the last action. Sorry for the inconvenience.";
filterContext.HttpContext.Response.Status = "500 " + message;
I read this http://blogs.msdn.com/b/kcwalina/archive/2007/01/30/exceptionhierarchies.aspx where the author recommends using existing .NET exception types to report usage errors. However, by introducing my custom exception, I just have to do a single check in my filter. Is my approach okay?
I like this approach for a couple of reasons.
First, it fails safely. If someone doesn't explicity throw a ClientException, then the exception details are not reported. Forgetting to display something is a lesser problem than accidently displaying something.
Secondly, it allows the decision about whether to display the exception to be made at the proper place. Not all IOExceptions are displayed, for example. Some may be, and others wont be. The specific exceptions can be caught and transformed anywhere in the call stack, so that tranformation can be made at a place where it is known to be correct.
Both of those things together mean that a future developer will not innappropriately change a whole class of exception to be displayed, or think that something won't be displayed when it actually will be.
Also, the purpose of the using a particular exception type is to determine later what action to take in response to that exception. "Display this message to the user" is a perfectly good action to specify. Once that decision has been made, then the exact nature of the exception is completely irrelivant. (The original problem may be put in the InnerException property, for logging purposes, of course.)
So, in my opinion, this is a good design.
Your approach is fine IMO but there are alternatives. (We're software developers so there are always alternatives.)
You could harness the Exception Data dictionary to store a flag indicating whether or not an exception is a client exception. Then you could have your filter check for the existence of the flag.
If your approach works for you then it is fine. And are you surprised that a Microsoft blog is recommending that you use their Exception class? ;)
There are some .NET library features and 3rd party OSS stuff that will only work with .NET exceptions however.
To get the best of both worlds you could always extend the .NET Exception object into your own.
I would use different Threshold values based on the type of exceptions, and these Threshold values would be associated with the exception messages.
Based on the particular Threshold value logic you may want to decide whether or not to show exception.
My concerns with this solution is that very likely these exceptions will typically be thrown by objects in a business layer (or model objects in MVC terminology). The usage you describe is really what I would consider to be a presentation concern.
Typically you'd need to rethrow whatever exception you have in your model, only to communicate whether or not the exception can be exposed to the user or not.
What do you expect the user to do with the information? If the user can fix the situation perhaps there should not be an exception to signal the state to begin with?
I would stick to catching specific exceptions per case and do presentation decisions at the spot. You may send out an exception, as caught, used as model to a view though. I would still let the controller decide, not whomever throws the exception.
I am using the ReportServices Web Services API and I want to determine the exceptions that can be thrown by it.
Is there an easy way to do that?
C# does not have exception specifiers like Java does, so the primary way to determine what exceptions a method throws is to look at the documentation and hope that the developers documented the possible exceptions.
Assuming you're talking about the SQL Server Reporting Services Web Service, it looks like their online API reference does mention exceptions. For example, for CreateSchedule it says:
This method throws an
rsUnsupportedParameterForModeException
exception if a non-null value is
specified for the SiteUrl parameter in
Native mode.
Alternatively, if you have lots of time, you can use Reflector to dig through the implementation of the API methods you call (and the methods they call, and so on...) to see what gets thrown.
Keep in mind that exceptions can still be raised due to internal errors. You can look up the documentation and have a look at the exceptions manually raised, but some NullReference or OutOfMemory can still occur.
Getting an complete list will be quite painful.