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.
Related
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.
public class PageNotFoundException : HttpException
{
public PageNotFoundException()
: base(404, "HTTP/1.1 404 Not Found")
{
}
}
The idea is that rather than typing this each time
throw new HttpException(404, "HTTP/1.1 404 Not Found")
I'd rather write
throw new PageNotFoundException();
I was going to add an overload for including the innerException however I will never use this in a try/catch block.
Would you consider this good practice?
i.e. Inheriting from an exception and passing hardcoded information to base(...).
I decided to rewrite my answer to be specific to your actual question, and in a more broad sense that an MVC application isn't the only thing these best-practices apply to.
(1) Answer. This is not good practice. You should use a exception builder method instead that throws HttpException directly.
public static void ThrowPageNotFoundException() {
throw new HttpException((Int32)HttpStatusCode.NotFound, "HTTP/1.1 404 Not Found");
}
(2) DO. Use exception builder methods (eg. the code I provided). This allows for you to avoid the extra performance cost of having your own exception type, and allows for it to be inlined. Members throwing exceptions do not get inlined. This would be the proper substitute for convenience throwing.
(3) DO. Use base class library exceptions whenever possible, and only create a custom exception when there is absolutely no base exception that meets the needed requirements. Creating custom exceptions adds deeper exception hierarchy, which makes debugging harder when it does not need to be, adds extra performance overhead, and also adds extra bloat to your code base.
(4) Do NOT. Throw the base class System.Exception. Use a specific exception type instead.
(5) Do NOT. Create custom exceptions for convenience. This is not a good reason for a custom exception, because exceptions are intrinsically costly.
(6) Do NOT. Create custom exceptions just to have your own exception type.
(7) Do NOT. Throw exceptions that can be avoided by changing the calling code. This would suggest that you have a usability error in the API rather than an actual problem.
Anyone who has read Framework Design Guidelines from the .NET development series will know these practices, and they are very good practices. These are the very practices that the .NET framework was built upon, and MVC as well.
If you are the one throwing the exception in the first place, then yes - it's OK. However, if you catch an HttpException and then try to throw a PageNotFoundException instead, you should put the original exception as the InnerException.
While this is a nice construct in your own code for your own use, one consideration is that it can promote coding by convention which can be dangerous when you're dealing with other/new developers.
In your own libraries, if you are consistent about throwing a PageNotFoundException whenever a 404 HttpException should be thrown, it might make more sense to catch (PageNotFoundException). However, when you start using other libraries that don't have your custom exception, you will miss 404 HttpExceptions thrown by other code. Likewise, if you have other developers contributing at a later date (or even your own additions in the future), the consideration that PageNotFoundExceptions are what's being caught by most of the functionality may be missed and new 404 HttpExceptions could be thrown in the new modules, which would likewise not be caught by copy/pasted calling code.
Basically, constructs like this increase the acclimation time required for working on the project, and should be handled in such a way that this cost is minimized (made sufficiently visible in an easy to find central shared objects library that isn't already too cluttered).
On the other hand, there is certainly value in centralizing the generation of your HttpExceptions if you're what looking for is essentially the factory pattern benefits; it may be worth just going with that instead if that's what you're trying to get out of it (throw ExceptionFactory.NewPageNotFound()).
I'm designing a class library that will be sent out to the public for use with their applications. It interacts with a custom db system that they need to install on their servers.
I'm having trouble deciding how to throw exceptions from this dll which is mainly a wrapper to the custom db system.
I assume I have to create custom exceptions that can indicate various types of errors, including validations, data integrity errors etc.
This dll will be eventually used by public facing web sites. I would like to provide a good feedback to the end user by throwing proper exceptions so that the site can make a decision to display them or not. But I'm not sure if it is possible to anticipate all the user input errors. In case of an unexcepted event, do I just throw a regular .net exception with the error message?
I have used many third party dlls that do not give you a clear way to handle the errors and I don't want to be one of them.
The only reason to creaqte a custom exception is if the calling code needs to catch it explicitly to know the difference between your exception and some other exception.
If the caller is going to treat your exception exactly the same as, say, InvalidOperationException, then you should throw InvalidOperationException instead.
See Choosing the Right Type of Exception to Throw.
You should rethrow custom exceptions where your DLL knows more about the error than is indicated in the exception you are catching, if you don't know about it, then you don't know MORE about it, just pass it along.
Just to be clear, this doesn't mean you can't throw your own exceptions on detecting errors.
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.