Centralized Exception Handling not workingHow do I handle async operations in Startup.Configure?ASP.NET Core Web API exception handlingProperly handling DbContexts in ASP.NET Core WebApiRunning Signalr in IIS on .Net Core - hub being hit but client sees 500 errorprevent application crashes when sending data over a closed websocket connectionHow to make elmah.io work well with ASP.NET Core and error handing middleware?Exception handler middleware not catchingException-Handling Middleware and PageCan ASP.Net Core ILogger.BeginScope wrap the middleware pipelineSerilog Logcontext properties are gone after exception handler

"Living" organ bank is it practical?

Why does VirtualBox crash macOS?

About the expansion of seq_set_split

Cause of continuous spectral lines

Why does Kathryn say this in 12 Monkeys?

Does the "6 seconds per round" rule apply to speaking/roleplaying during combat situations?

Where does this pattern of naming products come from?

What risks are there when you clear your cookies instead of logging off?

When conversion from Integer to Single may lose precision

What can plausibly explain many of my very long and low-tech bridges?

How to translate “Me doing X” like in online posts?

Traffic law UK, pedestrians

Turing patterns

Are there any existing monsters I can use as a basis for a baby skeleton statblock?

What do we gain with higher order logics?

You've spoiled/damaged the card

Did Darth Vader wear the same suit for 20+ years?

Do manufacturers try make their components as close to ideal ones as possible?

How can drunken, homicidal elves successfully conduct a wild hunt?

Why is the application of an oracle function not a measurement?

Strat tremolo bar has tightening issues

Why is the relationship between frequency and pitch exponential?

brain teaser - coin game

Implement Homestuck's Catenative Doomsday Dice Cascader



Centralized Exception Handling not working


How do I handle async operations in Startup.Configure?ASP.NET Core Web API exception handlingProperly handling DbContexts in ASP.NET Core WebApiRunning Signalr in IIS on .Net Core - hub being hit but client sees 500 errorprevent application crashes when sending data over a closed websocket connectionHow to make elmah.io work well with ASP.NET Core and error handing middleware?Exception handler middleware not catchingException-Handling Middleware and PageCan ASP.Net Core ILogger.BeginScope wrap the middleware pipelineSerilog Logcontext properties are gone after exception handler






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm testing centralized exception handling in my ASPNetCore application and wanted to see if an unexpected exception is thrown it is going to be correctly handled by app.UseExceptionHandler() middleware and logged to a specific logging target. I disconnected the SQL database expecting to see Database.EnsureCreated() method in the DbContext class constructor throwing System.Data.SqlClient.SqlException. The problem is that it does throw such an exception, but it appears locally instead of being handled by centrelized error handler. The final result is that a client never gets a response message explaining what happened with the status code 500.



enter image description here



It seems to be strange as the handler works correctly with an exception which I throw inside controllers.



Here is my centralized exception handler configuration:



app.UseExceptionHandler(appError =>

appError.Run(async context =>

var errorFeature = context.Features.Get<IExceptionHandlerFeature>();

if (errorFeature != null)

var exception = errorFeature.Error;

logger.LogError(exception.ToString());

await context.Response.WriteAsync("An unexpected error occurred! Try again later");



);
);


Could anyone tell me give me a hint on what I might be doing wrong? Has anyone come across a similar problem?










share|improve this question
























  • Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

    – Andre Kraemer
    Mar 24 at 21:35











  • @Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

    – aspdev
    Mar 25 at 8:34











  • Maybe it's related to the order of middleware.

    – Mohsen Esmailpour
    Mar 25 at 9:26

















0















I'm testing centralized exception handling in my ASPNetCore application and wanted to see if an unexpected exception is thrown it is going to be correctly handled by app.UseExceptionHandler() middleware and logged to a specific logging target. I disconnected the SQL database expecting to see Database.EnsureCreated() method in the DbContext class constructor throwing System.Data.SqlClient.SqlException. The problem is that it does throw such an exception, but it appears locally instead of being handled by centrelized error handler. The final result is that a client never gets a response message explaining what happened with the status code 500.



enter image description here



It seems to be strange as the handler works correctly with an exception which I throw inside controllers.



Here is my centralized exception handler configuration:



app.UseExceptionHandler(appError =>

appError.Run(async context =>

var errorFeature = context.Features.Get<IExceptionHandlerFeature>();

if (errorFeature != null)

var exception = errorFeature.Error;

logger.LogError(exception.ToString());

await context.Response.WriteAsync("An unexpected error occurred! Try again later");



);
);


Could anyone tell me give me a hint on what I might be doing wrong? Has anyone come across a similar problem?










share|improve this question
























  • Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

    – Andre Kraemer
    Mar 24 at 21:35











  • @Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

    – aspdev
    Mar 25 at 8:34











  • Maybe it's related to the order of middleware.

    – Mohsen Esmailpour
    Mar 25 at 9:26













0












0








0








I'm testing centralized exception handling in my ASPNetCore application and wanted to see if an unexpected exception is thrown it is going to be correctly handled by app.UseExceptionHandler() middleware and logged to a specific logging target. I disconnected the SQL database expecting to see Database.EnsureCreated() method in the DbContext class constructor throwing System.Data.SqlClient.SqlException. The problem is that it does throw such an exception, but it appears locally instead of being handled by centrelized error handler. The final result is that a client never gets a response message explaining what happened with the status code 500.



enter image description here



It seems to be strange as the handler works correctly with an exception which I throw inside controllers.



Here is my centralized exception handler configuration:



app.UseExceptionHandler(appError =>

appError.Run(async context =>

var errorFeature = context.Features.Get<IExceptionHandlerFeature>();

if (errorFeature != null)

var exception = errorFeature.Error;

logger.LogError(exception.ToString());

await context.Response.WriteAsync("An unexpected error occurred! Try again later");



);
);


Could anyone tell me give me a hint on what I might be doing wrong? Has anyone come across a similar problem?










share|improve this question
















I'm testing centralized exception handling in my ASPNetCore application and wanted to see if an unexpected exception is thrown it is going to be correctly handled by app.UseExceptionHandler() middleware and logged to a specific logging target. I disconnected the SQL database expecting to see Database.EnsureCreated() method in the DbContext class constructor throwing System.Data.SqlClient.SqlException. The problem is that it does throw such an exception, but it appears locally instead of being handled by centrelized error handler. The final result is that a client never gets a response message explaining what happened with the status code 500.



enter image description here



It seems to be strange as the handler works correctly with an exception which I throw inside controllers.



Here is my centralized exception handler configuration:



app.UseExceptionHandler(appError =>

appError.Run(async context =>

var errorFeature = context.Features.Get<IExceptionHandlerFeature>();

if (errorFeature != null)

var exception = errorFeature.Error;

logger.LogError(exception.ToString());

await context.Response.WriteAsync("An unexpected error occurred! Try again later");



);
);


Could anyone tell me give me a hint on what I might be doing wrong? Has anyone come across a similar problem?







asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 21:10







aspdev

















asked Mar 24 at 15:01









aspdevaspdev

359




359












  • Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

    – Andre Kraemer
    Mar 24 at 21:35











  • @Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

    – aspdev
    Mar 25 at 8:34











  • Maybe it's related to the order of middleware.

    – Mohsen Esmailpour
    Mar 25 at 9:26

















  • Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

    – Andre Kraemer
    Mar 24 at 21:35











  • @Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

    – aspdev
    Mar 25 at 8:34











  • Maybe it's related to the order of middleware.

    – Mohsen Esmailpour
    Mar 25 at 9:26
















Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

– Andre Kraemer
Mar 24 at 21:35





Did you try to run your program without a debugger attached? Depending on your configuration Visual Studio breaks on first chance exceptions

– Andre Kraemer
Mar 24 at 21:35













@Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

– aspdev
Mar 25 at 8:34





@Andre Kraemer Thanks. It works when I press Ctrl+F5, but I still don't understand why.

– aspdev
Mar 25 at 8:34













Maybe it's related to the order of middleware.

– Mohsen Esmailpour
Mar 25 at 9:26





Maybe it's related to the order of middleware.

– Mohsen Esmailpour
Mar 25 at 9:26












2 Answers
2






active

oldest

votes


















0














Your code looks fine to me. What you are experiencing is a First-Chance-Exception. This means that an exception has been thrown that might eventually get handled. During runtime your ExceptionHandler should perfectly handle your exception.



At debugging time however, Visual Studio breaks for that exception. The behaviour of Visual Studio can be configured in the Exception Settings (Debug > Windows > Exception Settings). See Microsoft Docs for more information on that.



So what you basically have to do is to tell Visual Studio to continue debugging on a SqlException






share|improve this answer






























    0














    You can use own middleware to handle exception as first-person



    public class ExceptionFilter: IExceptionFilter

    public void OnException(ExceptionContext context)

    String message = String.Empty;

    Type exceptionType = context.Exception.GetType();
    if (exceptionType == typeof(NotImplementedException))

    message = "A server error occurred.";
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
    context.Result = new RedirectResult("/Home/Index");

    else if (exceptionType == typeof(AppException))

    message = context.Exception.ToString();
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    context.Result = new RedirectResult("/Home/Index");

    //HttpResponse response = context.HttpContext.Response;
    //response.StatusCode = (int)status;
    //context.Result = new RedirectResult("/Home/Index");




    And in your Startup.cs



    app.UseMiddleware(typeof(ExceptionFilter));





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325126%2fcentralized-exception-handling-not-working%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Your code looks fine to me. What you are experiencing is a First-Chance-Exception. This means that an exception has been thrown that might eventually get handled. During runtime your ExceptionHandler should perfectly handle your exception.



      At debugging time however, Visual Studio breaks for that exception. The behaviour of Visual Studio can be configured in the Exception Settings (Debug > Windows > Exception Settings). See Microsoft Docs for more information on that.



      So what you basically have to do is to tell Visual Studio to continue debugging on a SqlException






      share|improve this answer



























        0














        Your code looks fine to me. What you are experiencing is a First-Chance-Exception. This means that an exception has been thrown that might eventually get handled. During runtime your ExceptionHandler should perfectly handle your exception.



        At debugging time however, Visual Studio breaks for that exception. The behaviour of Visual Studio can be configured in the Exception Settings (Debug > Windows > Exception Settings). See Microsoft Docs for more information on that.



        So what you basically have to do is to tell Visual Studio to continue debugging on a SqlException






        share|improve this answer

























          0












          0








          0







          Your code looks fine to me. What you are experiencing is a First-Chance-Exception. This means that an exception has been thrown that might eventually get handled. During runtime your ExceptionHandler should perfectly handle your exception.



          At debugging time however, Visual Studio breaks for that exception. The behaviour of Visual Studio can be configured in the Exception Settings (Debug > Windows > Exception Settings). See Microsoft Docs for more information on that.



          So what you basically have to do is to tell Visual Studio to continue debugging on a SqlException






          share|improve this answer













          Your code looks fine to me. What you are experiencing is a First-Chance-Exception. This means that an exception has been thrown that might eventually get handled. During runtime your ExceptionHandler should perfectly handle your exception.



          At debugging time however, Visual Studio breaks for that exception. The behaviour of Visual Studio can be configured in the Exception Settings (Debug > Windows > Exception Settings). See Microsoft Docs for more information on that.



          So what you basically have to do is to tell Visual Studio to continue debugging on a SqlException







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 25 at 8:50









          Andre KraemerAndre Kraemer

          2,28311226




          2,28311226























              0














              You can use own middleware to handle exception as first-person



              public class ExceptionFilter: IExceptionFilter

              public void OnException(ExceptionContext context)

              String message = String.Empty;

              Type exceptionType = context.Exception.GetType();
              if (exceptionType == typeof(NotImplementedException))

              message = "A server error occurred.";
              context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
              context.Result = new RedirectResult("/Home/Index");

              else if (exceptionType == typeof(AppException))

              message = context.Exception.ToString();
              context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
              context.Result = new RedirectResult("/Home/Index");

              //HttpResponse response = context.HttpContext.Response;
              //response.StatusCode = (int)status;
              //context.Result = new RedirectResult("/Home/Index");




              And in your Startup.cs



              app.UseMiddleware(typeof(ExceptionFilter));





              share|improve this answer



























                0














                You can use own middleware to handle exception as first-person



                public class ExceptionFilter: IExceptionFilter

                public void OnException(ExceptionContext context)

                String message = String.Empty;

                Type exceptionType = context.Exception.GetType();
                if (exceptionType == typeof(NotImplementedException))

                message = "A server error occurred.";
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                context.Result = new RedirectResult("/Home/Index");

                else if (exceptionType == typeof(AppException))

                message = context.Exception.ToString();
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = new RedirectResult("/Home/Index");

                //HttpResponse response = context.HttpContext.Response;
                //response.StatusCode = (int)status;
                //context.Result = new RedirectResult("/Home/Index");




                And in your Startup.cs



                app.UseMiddleware(typeof(ExceptionFilter));





                share|improve this answer

























                  0












                  0








                  0







                  You can use own middleware to handle exception as first-person



                  public class ExceptionFilter: IExceptionFilter

                  public void OnException(ExceptionContext context)

                  String message = String.Empty;

                  Type exceptionType = context.Exception.GetType();
                  if (exceptionType == typeof(NotImplementedException))

                  message = "A server error occurred.";
                  context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                  context.Result = new RedirectResult("/Home/Index");

                  else if (exceptionType == typeof(AppException))

                  message = context.Exception.ToString();
                  context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                  context.Result = new RedirectResult("/Home/Index");

                  //HttpResponse response = context.HttpContext.Response;
                  //response.StatusCode = (int)status;
                  //context.Result = new RedirectResult("/Home/Index");




                  And in your Startup.cs



                  app.UseMiddleware(typeof(ExceptionFilter));





                  share|improve this answer













                  You can use own middleware to handle exception as first-person



                  public class ExceptionFilter: IExceptionFilter

                  public void OnException(ExceptionContext context)

                  String message = String.Empty;

                  Type exceptionType = context.Exception.GetType();
                  if (exceptionType == typeof(NotImplementedException))

                  message = "A server error occurred.";
                  context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                  context.Result = new RedirectResult("/Home/Index");

                  else if (exceptionType == typeof(AppException))

                  message = context.Exception.ToString();
                  context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                  context.Result = new RedirectResult("/Home/Index");

                  //HttpResponse response = context.HttpContext.Response;
                  //response.StatusCode = (int)status;
                  //context.Result = new RedirectResult("/Home/Index");




                  And in your Startup.cs



                  app.UseMiddleware(typeof(ExceptionFilter));






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 15:37









                  BatuhanBatuhan

                  392314




                  392314



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325126%2fcentralized-exception-handling-not-working%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해