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;
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.

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
add a comment |
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.

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
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
add a comment |
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.

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
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.

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
asp.net-core
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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
add a comment |
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));
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
add a comment |
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
add a comment |
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
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
answered Mar 25 at 8:50
Andre KraemerAndre Kraemer
2,28311226
2,28311226
add a comment |
add a comment |
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));
add a comment |
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));
add a comment |
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));
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));
answered Mar 28 at 15:37
BatuhanBatuhan
392314
392314
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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