Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8266159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T05:03:29+00:00 2026-06-08T05:03:29+00:00

Say I have a constructor where it’s initialization can potentially throw an exception due

  • 0

Say I have a constructor where it’s initialization can potentially throw an exception due to reasons beyond my control.

FantasticApiController(IAwesomeGenerator awesome,
    IBusinessRepository repository, IIceCreamFactory factory)
{
       Awesome = awesome;
       Repository = repository;
       IceCream = factory.MakeIceCream();

       DoSomeInitialization(); // this can throw an exception
}

Ordinarily, when a Controller action in WebAPI throws an exception I can handle it via a csutom ExceptionFilterAttribute:

public class CustomErrorHandler
{
    public override void OnException(HttpActionExecutedContext context)
    {
        // Critical error, this is real bad.
        if (context.Exception is BubonicPlagueException)
        {
            Log.Error(context.Exception, "CLOSE EVERYTHING!");
            Madagascar.ShutdownAllPorts();
        }

        // No big deal, just show something user friendly
        throw new HttpResponseException(new HttpResponseMessage
        {
            Content = new StringContent("Hey something bad happened. " +
                                        "Not closing the ports though"),
            StatusCode = HttpStatusCode.InternalServerError;
        });
    }

So if I have a have a BoardPlane API method which throws a BubonicPlagueException, then my CustomerErrorHandler will shut down the ports to Madagascar and log it as an error as expected. In other instances when it’s not really serious, I just display some user friendly message and return a 500 InternalServerError.

But in those cases where DoSomeInitialization throws an exception, this does absolutely nothing. How can I handle exceptions in WebAPI controller constructors?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T05:03:31+00:00Added an answer on June 8, 2026 at 5:03 am

    The WebApi Controllers are created, and thus constructors called via HttpControllerActivators. The default activator is System.Web.Http.Dispatcher.DefaultHttpControllerActivator.

    Very rough examples for options 1 & 2 on github here https://github.com/markyjones/StackOverflow/tree/master/ControllerExceptionHandling/src

    Option 1 which works quite nicely involves the use of a DI container (you may well be using one already). I have used Ninject for my example and have used “Interceptors” Read More to intercept and try/catch calls to the Create method on the DefaultHttpControllerActivator. I know of at least AutoFac and Ninject that can do something simlar to to the following:

    Create the interceptor

    I don’t know what the lifetime scope of your Madagascar and Log items are but they could well be injected into your Interceptor

    public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
    {
        private ILog _log;
        private IMadagascar _madagascar;
    
        public ControllerCreationInterceptor(ILog log, IMadagascar madagascar)
        {
            _log = log;
            _madagascar = madagascar;
        }
    

    But keeping to the example in your question where Log and Madagascar are some kind of Static global

    public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
    {
    
        public void Intercept(Ninject.Extensions.Interception.IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch(InvalidOperationException e)
            {
                if (e.InnerException is BubonicPlagueException)
                {
                    Log.Error(e.InnerException, "CLOSE EVERYTHING!");
                    Madagascar.ShutdownAllPorts();
                    //DO SOMETHING WITH THE ORIGIONAL ERROR!
                }
                //DO SOMETHING WITH THE ORIGIONAL ERROR!
            }
        }
    }
    

    FINALLY Register the interceptor In global asax or App_Start (NinjectWebCommon)

    kernel.Bind<System.Web.Http.Dispatcher.IHttpControllerActivator>()
                .To<System.Web.Http.Dispatcher.DefaultHttpControllerActivator>().Intercept().With<ControllerCreationInterceptor>();
    

    Option 2 is to implement your own Controller Activator implementing the IHttpControllerActivator interface and handle the error in creation of the Controller in the Create method. You could use the decorator pattern to wrap the DefaultHttpControllerActivator:

    public class YourCustomControllerActivator : IHttpControllerActivator
    {
        private readonly IHttpControllerActivator _default = new DefaultHttpControllerActivator();
    
        public YourCustomControllerActivator()
        {
    
        }
    
         public System.Web.Http.Controllers.IHttpController Create(System.Net.Http.HttpRequestMessage request, System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            try
            {
                return _default.Create(request, controllerDescriptor, controllerType);
            }
            catch (InvalidOperationException e)
            {
                if (e.InnerException is BubonicPlagueException)
                {
                    Log.Error(e.InnerException, "CLOSE EVERYTHING!");
                    Madagascar.ShutdownAllPorts();
                    //DO SOMETHING WITH THE ORIGIONAL ERROR!
                }
                //DO SOMETHING WITH THE ORIGIONAL ERROR!
                return null;
            }
    
        }
    }
    

    Once you have your own custom activator the default activator can be switched out in the global asax :

      GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new YourCustomControllerActivator());
    

    Option 3 Of course if your initialisation in the constructor doesn’t need access to the actual Controllers methods, properties etc… i.e. assuming it could be removed from the constructor… then it would be far easier to just move the initialisation to a filter e.g.

    public class MadagascarFilter : AbstractActionFilter
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
        try{
              DoSomeInitialization(); // this can throw an exception
            }
            catch(BubonicPlagueException e){
        Log.Error(e, "CLOSE EVERYTHING!");
            Madagascar.ShutdownAllPorts();
                //DO SOMETHING WITH THE ERROR                           
            }
    
            base.OnActionExecuting(actionContext);
        }
    
    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    
        public override bool AllowMultiple
        {
            get { return false; }
        }
    
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have a label in a custom control. In the constructor I
Say I have a nice domain model, using (constructor) DI where needed. Now I
Let's say I have a PHP class called Color , it's constructor accepts various
If I have a constructor with say 2 required parameters and 4 optional parameters,
Lets say i have a Shape object that has a constructor like this: Shape(
Let's say I have the following structure declaration (simple struct with no constructor). struct
Say I have a class in Coffeescript: class MyGame constructor: () -> @me =
Say I have an object called FieldEdit . I define the function constructor for
Lets say we have this code that runs in the constructor: Dim initVectorBytes As
Let's say I have a class with an expensive constructor, and let's say I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.