Home > Enterprise >  in asp.net core, should i still use try-catch if i already have exception filter?
in asp.net core, should i still use try-catch if i already have exception filter?

Time:02-03

I'm talking about general functions in controller repositories: database stuff and logic. I presume that a-sync calls to-from other api should always be with try catch in case those fail. But about all the other stuff, should i still use try-catch or just one exception filter and be done with it?? I'm not sure what the common architecture use in the industry. thanks

CodePudding user response:

In my preference and experience Yes, even if you have exception filters in ASP.NET Core, you should still use try-catch blocks. While useful, exception filters might not be able to handle every possible error circumstance in your application.

Try-catch blocks let you handle failures that might happen inside the scope of a particular method or block of code as well as more precisely handle exceptions.

Additionally, they let you to capture exceptions and carry out further processing or logging before re-throwing the exception for handling by a higher-level handler, such an exception filter.

CodePudding user response:

It is possible to handle errors globally with the built-in middleware. So you need to create a class

namespace GlobalErrorHandling.Extensions
{
    public static class ExceptionMiddlewareExtensions
    {
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, 
            ILoggerManager logger)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode
                        .InternalServerError;
                    context.Response.ContentType = "application/json";
                    var contextFeature = context.Features
                        .Get<IExceptionHandlerFeature>();
                    if(contextFeature != null)
                    { 
                        logger.LogError($"Ooops. : {contextFeature.Error}");
                        await context.Response.WriteAsync(new ErrorDetails()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message = "Internal Server Error."
                        }.ToString());
                    }
                });
            });
        }
    }
}

and

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, 
    ILoggerManager logger) 
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.ConfigureExceptionHandler(logger);
    // ... the other code is omitted for the brevity
}   

Read more in this great article.

  • Related