1

I have problem with my simple app error handling middleware... When I tampered sql connect string, I get error but my middleware not catch it... someone know why?

{
    public class ErrorHandlingMiddleware : IMiddleware // we need to add it to tell ASP that this class is middleware
    {

        public ErrorHandlingMiddleware()
        {

        }
        //next - access to next middleware
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                await next.Invoke(context); // here we call next middleware?
            }
            catch(Exception e)
            {
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("Something went wrong");
            }
        }
    }
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,StudentSeeder seeder)
        {

            seeder.Seed();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyLibrus v1"));
            }
            //start of request

            app.UseMiddleware<ErrorHandlingMiddleware>();

            app.UseAuthentication();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<ErrorHandlingMiddleware>();
...

some one can tell me why does it not work? I don't have error in my swagger but in vs...

ruddnisrus
  • 187
  • 5
  • Your error handling middleware should be first in the pipepline to ensure all errors are caught, so move it to the top of your configure function. Secondly, if you're running in debug mode then it's possible the developer exception page is catching it. – ekke Jul 16 '21 at 10:36
  • @ekke You know how to fix it? – ruddnisrus Jul 16 '21 at 22:54

0 Answers0