1

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));
                }));
1
  • 2
    Validation doesn't throw exceptions and there is no way exception handler will be invoked in such way. Commented May 1, 2021 at 11:22

1 Answer 1

4

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;
            };
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.