ASP.NET Core Web API - Exception Middleware Question

Cenk 1,036 Reputation points
2022-12-24T10:35:36.96+00:00

Hello,

I am saving errors to the database and returning Internal Server Errors to the user as follows. I tried DI and injecting unit of work into middleware but I got some errors so I decided to implement this way. I wonder if this is a good solution or if are there any improvement areas.

namespace OyunPalasAPI.Middleware  
{  
    public class ExceptionMiddleware  
    {  
        private readonly RequestDelegate _next;  
        private static IConfiguration _configuration;  
          
        public ExceptionMiddleware(RequestDelegate next, IConfiguration configuration)  
        {  
            _next = next;  
            _configuration = configuration;  
        }  
  
        public async Task InvokeAsync(HttpContext httpContext)  
        {  
            try  
            {  
                await _next(httpContext);  
            }  
            catch (Exception ex)  
            {  
                await HandleExceptionAsync(httpContext, ex);  
            }  
        }  
  
        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)  
        {  
            await using (var sqlConnection =  
                         new SqlConnection(_configuration.GetSection("ConnectionStrings:OyunPalasDbContext").Value))  
            {  
                await using var cmd =  
                    new SqlCommand(  
                        "INSERT INTO [dbo].[APIError] ([Message],[RequestMethod],[RequestUri],[TimeUtc]) VALUES (@Message, @RequestMethod, @RequestUri, @TimeUtc)",  
                        sqlConnection);  
                sqlConnection.Open();  
  
                cmd.Parameters.AddWithValue("@TimeUtc", DateTime.Now);  
                cmd.Parameters.AddWithValue("@RequestUri", context.Request.Path.ToString());  
                cmd.Parameters.AddWithValue("@Message", exception.Message);  
                cmd.Parameters.AddWithValue("@RequestMethod", context.Request.Method.ToString());  
  
                cmd.ExecuteNonQuery();  
            }  
            context.Response.ContentType = "application/json";  
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;  
  
            await context.Response.WriteAsync(new ErrorDetails()  
            {  
                StatusCode = context.Response.StatusCode,  
                Message = "Internal Server Error."  
            }.ToString());  
        }  
    }  
}  
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-12-24T16:58:23.693+00:00

    The only issue that the app crashes on a logging (sql) error. This may be what you want.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.