I have an existing code base, which we catch exceptions etc.
Does anyone know if there is a way to list all the exceptions that either the code catches or raises so that I can do a review? reason for the review is the result of a pen test, which they flagged that the responses had too much details inside the exception.
Every day, thousands of innocent plants are killed by vegetarians.
VS can do a "Find in files" across a whole project or solution, and that can be a regex. So "\scatch\s" and "\sthrow\s" would find and list them all in the "Find" pane (which can be copied to the clipboard) or double clicked to go to each in turn)
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
In my experience the most interesting exceptions are the ones we do not throw or catch ourselves, but we get for free by calling some CLR class. Example: Image.FromFile() can throw an OutOfMemoryException when the file's format isn't recognized! Now how do you make sure your code base handles that properly???
Luc Pattyn [My Articles]
The Windows 11 "taskbar" is disgusting. It should be at the left of the screen, with real icons, with text, progress, etc. They downgraded my developer PC to a bloody iPhone.
Log them in FirstChanceException. Have a white / black dictionary / list as you work through them.
This event is only a notification. Handling this event does not handle the exception or affect subsequent exception handling in any way. After the event has been raised and event handlers have been invoked, the common language runtime (CLR) begins to search for a handler for the exception. FirstChanceException provides the application domain with a first chance to examine any managed exception.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
Look at the points where you expose data from the backend (typically a REST service or similar). If an exception is raised, you generally speaking just return "500 Internal Server error" without any further details - and (very important) log those details on the server.
In case you use exception to trigger responses like like "404 NOT FOUND" you need to make sure they do not show stack traces or internal details as well.
This is typically done in a central place in the response handler of the API so it will automatically kick in for any exception raised - you need to write this code and test it so you trust it no matter which exception is raised from the lower levels of the code. Then you do not need to hunt your entire code base for possible exceptions - which is an impossible task anyway as some system exceptions can be raised from anywhere.
Java tried to get the code to declare all exceptions so you could track it down (checked exceptions) but it was not a great success.
UPDATE: And make sure you only catch exceptions in 2 cases:
1) When you can FIX the issue - i.e. no error will be returned to the client, and hence no information will be leaked. Example: You want to read some data from a disk cache. If the read throws an exception catch it and recalculate the data.
2) When you can throw an exception with more details. Example: You try to read the data but the exception just says "Access denied". You know what you where trying to read and which user you where running as, so catch it and throw a new exception adding these datails - keeping the original exception as inner exception.
Probably, but hard to say without any details. I am surprised it is not the default behavior of whatever framework he is using, so maybe the default was just changed to make it easier to debug. In ASP.NET you do for example get the "to read the error details, change this setting" message - and someone not understanding the impact might just have followed these instructions. In that case the only thing he needs to do is revert that setting. But I am not going to google the solution to every imaginable framework out there, just because the poster forgot to mention what they are using.
..then have your exceptions inherit from a custom class inheriting from Exception. For logging, use FirstChanceException as suggested by Gerry; it will show a lot more than the exceptions you throw yourself.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
list all the exceptions that either the code catches or raises so that I can do a review
That process would need to find that those in all of the libraries that you use also.
reason for the review is the result of a pen test,
Probably because you have an API and you are returning the exception stack trace as part of the API error handling. The solution to that is the following
1. Catch all exceptions so "catch(Exception e)" in your API layer.
2. Log the exception. You should of course already be doing this.
3. Return an error result from the API. Do not return the exception. Probably 500. But over time you can differentiate this in the error handling code.
I would suggest that you also create an id and log that as well and return that as part of the error message. That way you can track an error reported from a caller back to the specific log entry. You can use a GUID but it is going to be more user friendly, especially if a UI is involved, if you create a simple id. It can rotate over time because the context of the error (when reported) is enough to localize in the logs.
There is no way to do it in general, not even in theory.
TryGetNonEnumeratedCount is neat, but only actually outputs the count when it is called on a collection that knows its count. For general enumerables such as WhereListIterator, it returns false. So OK, it doesn't evaluate the enumerable, but it also doesn't help.
Any on a WhereListIterator has to evaluate until it finds an element or runs out of input. There's nothing else it could do. BTW Any includes TryGetNonEnumeratedCount-like tricks, examining the type of the object it is called on, and if it is an ICollection then it just checks whether its count is zero (there are additional details but they don't help here either), but those tricks cannot apply to a filtered enumerable.
If there was any method that could in general predict whether a filtered enumerable is going to have anything in it (without iterating through it), that would have strange implications. It would act as a powerful oracle (of the theoretical computer science variety) that can extract information from a black box function without ever actually evaluating the function. Spooky.
thanks, Harold, as I'd expect from you, a very thoughtful reply.
I've found very little documentation on 'TryGetNonEnumeratedCount so far. My impression in the SO thread cited is that this new Linq method is somehow more efficient.
Given .Any short-circuits when it encounters a first instance: I find myself wondering if under-the-hood .Any is in any way more "efficient" in a function that returns an IEnumerable ... compared to invoking Count().
In this context: in a loop where a series of functions are called in sequence, and the goal is to exit the loop when any function returns an empty IEnumerable ... .Any can be used while testing for null or == default are useless.
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
TryGetNonEnumeratedCount is always efficient, but that's because in the case that the enumerable doesn't already know its count, instead of falling back to counting elements one-by-one (as Count does), it just gives up. It is Count but without the default/slow path, only the special cases. I wouldn't really call it "more efficient", it's more like a niche thing that you can use when you would like to have a count but you don't really need it (such as to create a collection with an initial size, which isn't worth counting one-by-one for, but if getting the count is basically free then you may as well use it).
Any can certainly be more efficient than Count, thanks to the early-out. In some cases Count is actually more efficient, but let's put that aside, that's not really relevant to the case you're dealing with.
So far I have no specific reason to think that there is any better solution than Any. Maybe if there is some special property of the Mystery Function that's being called, or of the overall algorithm, there may be some other technique.
1) "TryGetNonEnumeratedCount ... in the case that the enumerable doesn't already know its count, instead of falling back to counting elements one-by-one (as Count does), it just gives up"
If an IEnumerable "knew" its count ... is that a contradiction in terms ? Clearly, some collections "know" their count, because it is a Property not a method.. But, a generic IEnumerable created at run-time ?
2) "In some cases Count is actually more efficient"
fascinating; I try to imagine a case of a generic IEnumerable where Count() would be more efficient ... but, draw a blank
3) if you had a function that returned a generic IEnumerable, and in that Function you used Count(): would there be any structural differences between that returned result and a returned result IEnumerable you had never used Count on.
4) comparing a a generic IEnumerable you used Count() on with one you used Any() on: would there be any structural differences ?
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
If an IEnumerable "knew" its count ... is that a contradiction in terms ?
Not really. For example, a List<T> is also an IEnumerable<T>; the List<T> "knows" its count.
The TryGetNonEnumeratedCount method simply attempts to cast the IEnumerable<T> to a few "pre-counted" interfaces at run-time, and returns the Count property from the first one that succeeds. You can see the source code on GitHub:
It tries ICollection<T>, IIListProvider<T>, and the non-generic ICollection. That should cover most cases, although it notably doesn't try the IReadOnlyCollection<T> introduced in .NET 4.5 - I can't find an official comment, but this SO thread[^] discusses that.