Although not much popular in Micro-services & Restful architecture, (I'm presuming). We prefer to raise graceful business excetion by means of custom exception classes derived from ApplicationException.
Is there any mechanism to self declare, by some compile feature that
Ex1, Ex2, Ex3 are the possible business exceptions thrown by a class service.
If you're already familiar with WCF, hope you have got it. I'm Something on the lines of WCF
(Exception contract)
Example:
public class BlobChecksumMatchException : ApplicationException
{
public BlobChecksumMatchException(string msg) : base(msg)
{
}
}
EDIT:
(Not to mention Exception base of course can be thrown for whatsoever reason, I'm just looking out for predefining business exception classes)
There's no such built-in mechanism in C# or .NET. However, you have a couple of workaround options:
1) If that information is for human consumption, you can use XML documentation comments as pointed out by Andreas Zita.
2) If you need a machine-readable mechanism, you could declare a custom "ThrowsException" attribute and apply it to your class or methods, then retrieve these using reflection:
class MyBusinessClass
{
[ThrowsException(typeof(Ex1))]
[ThrowsException(typeof(Ex2))]
public void DoSomething() {}
}
Note however that reflection is expensive, depending on your performance requirements you might need to implement some caching mechanism for that information.
Related
we are trying to implement Logging in our application using AOP (and PostSharp by the way but this question relates to any AOP framework).
The problem we are facing is that the information we get is like:
Entering method XXX with parameters:
parameter content if it is a value type.
anything in the ToString() override if it is done.
classname if the ToString() is not overridden.
This information is not very useful as normally what we get is the 3rd case. We are creating also LOTS of non useful information.
If you have used AOP for logging in any product how did you manage this problem?
Thanks in advance.
A few approaches:
Put a common interface on types that you want to log. (ILoggable, for example). Implementing that interface will give your aspect the ability to log exactly what you want. The downside is that you have to implement/maintain ILoggable for every object that you might log.
Use reflection (which is what I did in this audit example on my blog. It uses an MVC ActionFilter, but the principle is the same). The trade-offs are spelled out in the blog post, but basically it's complexity of using reflection and performance concerns, depending on how much you are logging and how often.
Use serialization. Given an object, serialize it to Json or XML or whatever, and log that string. Depending on what you're doing with the logs, this could range from perfect to worthless, and depending on how the serialization works and how complex the objects are, this could be a performance issue too.
I work on a new kind of AOP Framework to respond on the missing features of existing AOP Framework. You can find my open source project here : NConcern .NET AOP Framework
One of the differences with others is to allow you to develop your advice with System.Linq.Expression to avoid boxing/unboxing, reflection and hash jump based on type. It is a little harder to develop using Expression for beginner but easy for an advanced developer.
Example a simple example of logging (into console) without rewrite your business, reflection and boxing.
a business : Calculator
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
your logging Aspect implemented by linq expression to describe how Advice must work.
public class Logging : IAspect
{
//this is not an advice, this method is called to produce advices
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//generic presentation method
var presentation = typeof(Presentation). GetMethod("Of");
//example log on exception
//instance, arguments and exception are Expressions
yield return Advice.Linq.After.Throwing((instance, arguments, exception) =>
{
Expression.Call
(
typeof(Console).GetMethod("WriteLine",...),
Expression.Call
(
typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) }),
Expression.NewArrayInit(typeof(string), arguments.Select(argument => argument.Type == typeof(string) ? argument : ...).ToArray())
)
)
}
}
}
I want to create an abstract class with an common exception handling pattern:
public abstract class Widget
{
public IFoo CreateFoo()
{
try
{
CreateFooUnsafe();
}
catch(Exception ex)
{
throw new WidgetException(ex, moreData, evenMoar);
}
}
protected abstract IFoo CreateFooUnsafe();
}
The intention is to have a standard exception handling pattern across all deriving objects. The abstract CreateFooUnsafe() method should not be expected to contain any exception handling. Implementations would probably a single line of return new Foo(...)
What I want to know is whether there are any standard naming conventions associated with this pattern, particularly where exception-throwing code is expected?
The names above seem somewhat appropriate, but not entirely without smell.
This appears to be an example of the template method pattern.
Template method is a pattern which can be expressed in many object-oriented languages by using a public non-virtual function to implement some over-arching behavior, and a protected virtual (or abstract) method to supple the concrete behavior in subclasses.
In your example, you are using the template method to catch all exceptions bubbling out of the inner implementation and wrapping them in a custom exception type. One comment I would make about this specific practice, is that it only makes sense if you can add contextual information that would allow calling code to better handle the exception. Otherwise, it may be better to simply allow the source exceptions to propogate out.
The short answer is no.
There is no convention in the Template Pattern to designate what type and when an exception is thrown. That kind of information is included in some section of the documentation as per MSDN. Using C# and XML comments you can easily generate such documentation.
I'm under the impression that there might be a naming convention in place for the Template Pattern itself sans any referencing to exception handling. As I understand it, naming might look like this:
public abstract class Widget
{
public void PerformAction()
{
this.PerformActionImpl();
}
protected virtual void PerformActionImpl(){}
}
Where Impl is a shorthand for "Implementation". Personally I don't like that naming style so don't use it but I'm sure I've read it somewhere semi authoritative that that is "the" way to do it.
I wouldn't use any of this in your case however as what you really to seem to want to either Factory or AbstractFactory.
..
With regard to your exception query, it seems to me the code is a little inside out tho I disagree with some of the other comments depending on your circumstances.
Wrap and throw is an entirely valid exception handling technique.
The additional context provided by the type of the exception itself may well be enough to route the exception to an appropriate handler. i.e. you've transformed an Exception into a WidgetException which one would expect then has context within your application. So that might well be good enough.
Where you've done the wrapping I do however disagree with.
I would do the catching wrapping and throwing from within the subclass implementation of the virtual method as only that subclass is going to have enough understanding of what it's doing to know whether the Exception is indeed a WidgetException and therefore wrap and throw or something a little more hairy that should propagate.
The code as it stands is making some massive assumptions about the cause of the exception and in that sense rendering any use of a custom exception next to useless. i.e. everything is now a WidgetException.
So while I believe type alone could be enough to contextualise the exception I dont believe the code is making that decision in the right place. I understand the motivation behind the implementation you've chosen as it seems like a really tasty shortcut, "the myth of the all knowing base class" but the mere fact that you declared it as abstract should provide a significant clue that the class is intended to be ignorant by design.
So with respect to the crosscutting concern of exception handling I don't think you should looking so much for a pattern to make your life easier but rather a framework to abstract all the guff away.
For example the Enterprise Library.
There are several different patterns swimming about in the code above. Among other things, it looks a bit like the Abstract Factory pattern, i.e., you've got an abstract class which is implementing a factory method that returns concrete objects which implement a specific interface.
As to whether this sort of exception handling is a good idea or not -- I would tend to agree with the other folks, that I can't typically see a lot of value in this approach. I see what you're trying to do, namely, provide a single sort of exception to handle, much as the CreateFoo() returns a single interface (IFoo). But the only benefit I can think of to that approach is if you provide some interesting and relevant troubleshooting information in the WidgetException (e.g., some database or service connection strings, or some special processing logic around the stack trace). If you're just wrapping the original exception so that your clients can deal with a WidgetException, you haven't really accomplished much: they could just as easily deal with the base Exception type.
I'm looking at creating a helper method to set an exception's message, automatically setting String.Format, adding in inner exceptions, setting commandline exit codes, etc; something like:
public static void MyExceptionHelper(ExitCode code, string message) {}
public static void MyExceptionHelper(ExitCode code, Exception e) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message, params object[] args) {}
// etc...
The BCL has got a few static classes around that does that sort of thing (eg System.ThrowHelper in mscorlib).
Where is the best place to put these? As overloaded constructors on the exception, in a separate static class (like the BCL), as static methods on the exception itself, or somewhere else?
I'd recommend the Exception application block in EnterpriseLibrary, it has a very elegant design for dealing with exceptions and if you don't want all of EntLib I'd recommend copying their interface.
For methods like this, I prefer overloaded constructors. You're clearly using it to create a new object, and that's what a constructor is for.
Once you get into the world of static methods, it's not always clear where they should end up. You'll need to analyze who will use them and how they will be used, then examine the pros and cons of each potential location. Then, you will know where to put them.
I'd just make these constructors for your exception class.
Most of the time, the exception helpers in the BCL are there to support localization (which is usually wrapped up in the SR internal class you'll find in almost all .NET BCL assemblies.) The general idea is that you use a helper method to pass in some basic data for an exception, and the helper handles the retrieval of resources and formatting of data for you to create the exception. The benefit is that you centralize code for exceptions that may be thrown from multiple locations, but which need to be created in the same way. So generally, same idea as any other utility class or inherited object...promotes reuse and maintainability.
As for where to put them...I like to have an "internal area" in each of my assemblies with an exception helper, resource helper, and other internal "assembly support" types.
This looks like you have enough custom behavior to want to derive your own exception class, and put this behavior on it. Depending on whether or not you want to interact with the base Exception sine qua Exception later on, you might want to have these be constructors on your derived class that set the base to the passed-in exception, and do your modifications on that exception from within your class; polymorphism will allow that instance to be recast up to a base Exception for interaction from there.
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
public interface ICut
{
void Cut();
}
public class Knife : ICut
{
void ICut.Cut()
{
//Cut Something
}
}
And to use the Knife object:
ICut obj = new Knife();
obj.Cut();
Would you recommend this method of interface implementation? Why or why not?
EDIT:
Also, given that I am using an explicit interface the following would NOT work.
Knife obj = new Knife();
obj.Cut();
To quote GoF chapter 1:
"Program to an interface, not an implementation".
"Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)
ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
I've only used it in scenarios where I want to restrict access to certain methods.
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
return "";
}
void IWriter.Write(string message)
{
// Implementation
}
}
public class Foo
{
readonly MessageLog _messageLog;
IWriter _messageWriter;
public Foo()
{
_messageLog = new MessageLog();
_messageWriter = _messageLog;
}
public IReader Messages
{
get { return _messageLog; }
}
}
Now Foo can write messages to it's message log using _messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.
Yes. And not just for testing. It makes sense to factor common behaviour into an interface (or abstract class); that way you can make use of polymorphism.
public class Sword: ICut
{
void ICut.Cut()
{
//Cut Something
}
}
Factory could return a type of sharp implement!:
ICut obj = SharpImplementFactory();
obj.Cut();
This is a bad idea because their usage breaks polymorphism. The type of the reference used should NOT vary the behavior of the object. If you want to ensure loose coupling, make the classes internal and use a DI technology (such as Spring.Net).
There are no doubt certain advantages to forcing the users of your code to cast your objects to the interface types you want them to be using.
But, on the whole, programming to an interface is a methodology or process issue. Programming to an interface is not going to be achieved merely by making your code annoying to the user.
Using interfaces in this method does not, in and of itself, lead to decoupled code. If this is all you do, it just adds another layer of obfuscation and probably makes this more confusing later on.
However, if you combine interface based programming with Inversion of Control and Dependency Injection, then you are really getting somewhere. You can also make use of Mock Objects for Unit Testing with this type of setup if you are into Test Driven Development.
However, IOC, DI and TDD are all major topics in and of themselves, and entire books have been written on each of those subjects. Hopefully this will give you a jumping off point of things you can research.
Well there is an organizational advantage. You can encapsulate your ICuttingSurface, ICut and related functionality into an Assembly that is self-contained and unit testable. Any implementations of the ICut interface are easily Mockable and can be made to be dependant upon only the ICut interface and not actual implementations which makes for a more modular and clean system.
Also this helps keep the inheritance more simplified and gives you more flexibility to use polymoprhism.
Allowing only callers expecting to explicit interface type ensures methods are only visible in the context they are needed in.
Consider a logical entity in a game and u decide that instead of a class responsibile for drawing/ticking the entities you want the code for tick/draw to be in the entity.
implement IDrawable.draw() and ITickable.tick() ensures an entity can only ever be drawn/ticked when the game expects it to. Otherwise these methods wont ever be visible.
Lesser bonus is when implementing multiple interfaces, explicit implementations let you work around cases where two interface method names collide.
Another potential scenario for explicitly implementing an interface is when dealing with an existing class that already implements the functionality, but uses a different method name. For example, if your Knife class already had a method called Slice, you could implement the interface this way:
public class Knife : ICut
{
public void Slice()
{
// slice something
}
void ICut.Cut()
{
Slice();
}
}
If the client code doesn't care about anything other than the fact that it can use the object to Cut() things, then use ICut.
Yes, but not necessarily for the given reasons.
An example:
On my current project, we are building a tool for data entry. We have certain functions that are used by all (or almost all) tabs, and we are coding a single page (the project is web-based) to contain all of the data entry controls.
This page has navigation on it, and buttons to interact with all the common actions.
By defining an interface (IDataEntry) that implements methods for each of the functions, and implementing that interface on each of the controls, we can have the aspx page fire public methods on the user controls which do the actual data entry.
By defining a strict set of interaction methods (such as your 'cut' method in the example) Interfaces allow you to take an object (be it a business object, a web control, or what have you) and work with it in a defined way.
For your example, you could call cut on any ICut object, be it a knife, a saw, a blowtorch, or mono filament wire.
For testing purposes, I think interfaces are also good. If you define tests based around the expected functionality of the interface, you can define objects as described and test them. This is a very high-level test, but it still ensures functionality. HOWEVER, this should not replace unit testing of the individual object methods...it does no good to know that 'obj.Cut' resulted in a cutting if it resulted in the wrong thing being cut, or in the wrong place.
In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET?
More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.
Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:
throw new Exception("Bar happened in Foo");
throw new FooException("Bar happened");
throw new FooBarException();
where
class FooException : Exception
{
public FooException(string message) ...
}
and
class FooBarException : FooException
{
public FooBarException()
: base ("Bar happened")
{
}
}
I prefer the 3rd option, because I see it as being an OO solution.
Inherit from System.Exception. System.ApplicationException is useless and the design guidelines say "Do not throw or derive from System.ApplicationException."
See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.
I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.
The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.