nAviD
nAviD

Reputation: 3281

UseExceptionHandler is not working with validation errors

In Asp.Net Core 5 I am using UseExceptionHandler to handle exceptions globally and it works fine unless I send an invalid object. For example I send an object with null value for the required property "Name" I receive the following error in client but the Run function does not hit in debugger.

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1" ,"title":"One or more validation errors occurred.","status":400,"traceId":"00-2428f0fb9c415843bca2aaef08eda6f6-11ea476efb792849-00","errors":{"Name":["The field Name is required"]}}

(as the first middleware in the pipeline :)

     app.UseExceptionHandler(a => a.Run(async context =>
                {
//this does not being exceuted for validation errors
                    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                    var exception = exceptionHandlerPathFeature.Error;
    
                    var exceptionManager = a.ApplicationServices.GetRequiredService<IExceptionManager>();
                    await context.Response.WriteAsJsonAsync(exceptionManager.Manage(exception, context));
                }));

Upvotes: 1

Views: 1142

Answers (1)

Ghadeer Ismael
Ghadeer Ismael

Reputation: 71

This may help you.

services.AddControllers().ConfigureApiBehaviorOptions(options =>
        {
            options.InvalidModelStateResponseFactory = context =>
            {
                var errors = context.ModelState.Keys
                                        .SelectMany(key => context.ModelState[key].Errors.Select(x => $"{key}: {x.ErrorMessage}"))
                                        .ToArray();

                var apiError = new CustomErrorClass() 
                {
                    Message = "Validation Error",
                    Errors = errors 
                };

                var result = new ObjectResult(apiError);
                result.ContentTypes.Add(MediaTypeNames.Application.Json);

                return result;
            };
        });

Upvotes: 4

Related Questions