Skip to main content

Exception Handling With Exception Policy

This is how I would think of an application at the very basic level:
Now this works great. But one thing that is missing in this picture is Exception Handling. In many cases we pay very less attention to it and take it as "we'll cross that bridge when it'll come to that". We can get away with this as in many application as exceptions does not stop it from being in the state "is the application working" as long as we code it carefully and at the very least handling the exceptions in code blocks.
This works. But we end up having try catch and if else everywhere and often with messy or no direction to what type of exception is to be handled where and how. Nonetheless, when it comes down an enhancement that depends upon different types exceptions, we will end up writing/modifying code every where, resulting in even messier code. I'm sure no one wants that. Even, in scenarios, a custom handler is not the answer either. Cause this way we will still need to make changes all over our code where we have used that handler.



The hero that can save us from this predicament is this namespace: ᕙ(`▿´)ᕗ
 Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
So the idea is very simple.
- Think about what kind of exceptions may occur in you application like read exception, write exception, heck even not implemented exception. (at the very least the  "awesome" application can have "awesomegenericexception"
- Define a policy for each. For each policy we'll have our own implementation or channel in to an existing implementation.
- apply these policies where necessary.

How it looks:
- in config:
<configSections>
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<exceptionHandling>
    <exceptionPolicies>
        <add name="AwesomeExceptionPolicy">
            <exceptionTypes>
                <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                    postHandlingAction="ThrowNewException">
                    <exceptionHandlers>
                        <add name="Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                            exceptionMessage="Awesome Exception Occured." exceptionMessageResourceType=""
                            exceptionMessageResourceName="Awesome Exception Occured. This is so awesome that you are going to get a text message for it :)."
                            wrapExceptionType="Awesome.Lib.Exceptions.AwesomeExceptionPolicyImpl, Awesome.Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
                    </exceptionHandlers>
                </add>
            </exceptionTypes>
        </add>
    </exceptionPolicies>
</exceptionHandling>

- in code "the boss of exceptions":public class ExceptionManagerFactory : IProvider
{
    ExceptionManager exceptionManager;
    public Type Type
    {
        get
        {
            return this.GetType();
        }
    }
    public object Create(IContext context)
    {
        return GetExceptionManager();
    }
    public ExceptionManager GetExceptionManager()
    {
        if (exceptionManager == null)
        {
            IConfigurationSource config = ConfigurationSourceFactory.Create();
            ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config);
            this.exceptionManager = factory.CreateManager();
        }
        return this.exceptionManager;
    }
}

- in code "the injection":Kernel.Bind<ExceptionManager>().ToProvider<ExceptionManagerFactory>().InSingletonScope();

- in code "the implementation":public class AwesomeExceptionPolicyImpl : ApplicationException
{
    public AwesomeExceptionPolicyImpl(string message)
        : base(message)
    { }     public AwesomeExceptionPolicyImpl(string message, Exception innerException)
        : base(message, innerException)
    {
        Console.WriteLine("to err is human :)");
    }
}
- in code "the use":
ExceptionManager exManager; // injection. Can be done in the super duper base class.
exManager.Process(() =>
{
 YouMyAwesomeTask();
}, "AwesomeExceptionPolicy");


private void YouMyAwesomeTask()
{
 // do the awesome task.
}


Here, I am only implementing the policy for System.Exception. But this can be for other exception types as well. Where the type does not need to be anything more than just a type or even just a message.


- So when it will come down to future modification we will only have to touch one class. Or in the worst case very little change in the code.
- And the overall outcome is even better you write less code. While implementing your method you only think about what policy does it fall under. How that is handled/implemented that's not your problem.
- Even you can make up policy as you go and implement them at later point or channel them to one implementation.
- And ofcourse, CLEAN CODE.

\ (•◡•) /

Comments

Popular posts from this blog

Reimagining Logs: Building AI powered Conversational Observability System

It is mid-2025 and the cogs of AI are at full speed. So we (I and Mobin) decided to do our own AI project. We called it "IntelliLogs".  IntelliLogs at a glance: Demo:  https://www.youtube.com/watch?v=OXMlORwyMQk In this post I will describe why we did what we did, what is it that we did and how we did it. I will share my personal experience. I am hoping this will, at least, be an interesting read. Table of contents: Why IntelliLogs What is IntelliLogs How IntelliLogs was developed Future of IntelliLogs Conclusion References Why IntelliLogs: Personal motivation 💪 to this were: Explore and experience what does an AI app look like from an architectural and engineering perspective Explore the realm of Huge LLMs (eg: GPT-4.1-170B,  Gemini Pro etc) vs small LLMs (eg: granite-7b, gemma-4b) Explore the possibilities of model tuning / making a model without being a data scientist. How easy or hard it is, what tools available etc. We also wanted to tackle a "not too far from ...

Smart wifi controlled irrigation system using Sonoff and Home Assistant on Raspberry Pi - Part 1

If you have a backyard just for the sake of having one or it came with the house and you hate watering your garden or lawn/backyard then you have come to the right place. I genuinely believe that it is a waste of my valuable time. I would rather watch bachelorette on TV than go outside, turn on tap, hold garden hose in hand to water. Too much work!! Luckily, we have things like sprinkler system, soaker etc which makes things a bit easy. But you still have to get off that comfy couch and turn on tap (then turn off if there's no tap timer in place). ** Skip to the youtube video part if reading is not your thing   When I first moved into my house at first it was exciting to get a backyard (decent size), but soon that turned on annoyance when it came down maintaining it, specially the watering part. I laid bunch sprinklers and soaker through out the yard and bought tap timer but I still needed to routinely turn on the tap timer. Eventually few days ago I had enough of this rub...

The story of a Hack Job

"So, you have hacked it" -- Few days ago one of the guys at work passed me this comment on a random discussion about something I built. I paused for a moment and pondered: Do I reply defending how that's not a hack. OR Do I just not bother I picked the second option for 2 reasons: It was late. It probably isn't worth defending the "hack vs" topic as the comment passed was out of context. So I chose the next best action and replied "Yep, sure did and it is working great.". I felt like Batman in the moment. In this post I will rant about the knowledge gap around hacking and then describe about one of the components of my home automation project (really, this is the main reason for this post) and use that as an example how hacking is cool and does not always mean bad. But first lets align on my definition of hacking: People use this term in good and bad, both ways. For example: "He/she did a hack job" -- Yeah, that probably...

Hall of justice - Authorisation Greeting System

Ever since I watched the Young Justice EP-1 the security system of the Hall Of Justice and Mount Justice wow-ed me. After all it was built by Batman. You see similar AI driven voice guided system in pretty much in all sci-fi series these days. I always dreamed of having something similar of my own. Well, now I have it (sort of). Although we not quite in the flying cars era yet (disappointment) but IOT powered locks are somewhat normal these days. The adoption rate is great.  Some background: What is this Hall Of Justice Authorisation system? This is the security system that Batman built for Hall Of Justice. The movies haven't shown it yet but there're several scenes in the animated series and comic books. Basically, it is a AI powered voice guided intelligent security system that scans bio signatures (like retina, body dimensions, temperature, heart rate) through a scanning device and identifies which member of the justice league it is, logs entry then gr...

Jenkins on k8s - can it be this easy?

 As developers or devops we have had a somewhat love and hate relationship with Jenkins like "love oss based ci/cd that can be hosted on any environment with ranges of community plugins for pretty much anything" BUT "hate messy UI, lack of documentations, difficult to configure" etc etc. But this post isn't about pros and cons of Jenkins, rather it is about how you can get Jenkins on your k8s super quick and easy (using Merlin). Git Repo:  https://github.com/alinahid477/jenkinsonk8s Table of contents: Why Jenkins Why Merlin for Jenkins What is Merlin for Jenkins How Merlin for Jenkins works How Jenkins on k8s work Some anticipated FAQs Why Jenkins Jenkins remains a popular choice when it comes to CICD solution with a massive community of users and contributors (despite the fact there are new cool kids in block like Tekton etc). The way I see it (because of our love and hate relationship with it) "Jenkins is not CICD tool that you want it's the CICD t...

Do you even Kubernetes ? - in private cloud

Kubernetes (“koo-burr-NET-eez”) /κυβερνήτης/ - Can be used as noun or verb. Noun "helmsman" or "pilot" or "Orchestrator". We use Kubernetes to achieve resiliency for our application. Verb Perform the act of doing Kubernetes. When done using TKG it is easy but can be super hard if the right tool is not used. Do you even Kubernetes? If I were to survey about how many people in IT industry (regardless of role) knows or at least heard about Kubernetes I would be very surprised if the percentage came out any less than at least 80%. I am curious though, How many people have actually deployed on Kubernetes? How many people have created a Kubernetes cluster? How? The answer could go either way of "Yeah, it's easy" OR "Dude!! it's hard". This is because, in my opinion, it all depends on choosing the right toolset that are fit for purpose. In this post I will create a Kubernetes cluster and deploy a microservice application End-To-End, th...