josephwoodward / GlobalExceptionHandlerDotNet

Exception handling as a convention in the ASP.NET Core request pipeline
MIT License
272 stars 32 forks source link

User configured global message formatter is never used #4

Closed pnevill closed 6 years ago

pnevill commented 6 years ago

In the example below, I would expect the message "Something went wrong!" to be returned whenever any exception other than a DivideByZeroException is encountered.

           app.UseWebApiGlobalExceptionHandler(x =>
            {
                x.MessageFormatter(exception => JsonConvert.SerializeObject(new
                {
                    error = new
                    {
                        message = "Something went wrong!"
                    }
                }));

                x.ForException<DivideByZeroException>().ReturnStatusCode(HttpStatusCode.BadRequest).UsingMessageFormatter(
                    exception => JsonConvert.SerializeObject(new
                    {
                        error = new
                        {
                            exception = exception.GetType().Name,
                            message = exception.Message
                        }
                    }));
            });

This however doesn't happen, because the HandleExceptionAsync method creates a new instance of DefaultExceptionConfig, which provides its own Formatter.

Removing the Formatter from the DefaultExceptionConfig seems to solve my issue, but may have result in issues for other scenarios.

public class DefaultExceptionConfig : IExceptionConfig
    {
        public HttpStatusCode StatusCode { get; set; }
        public Func<Exception, string> Formatter { get; set; }

        public DefaultExceptionConfig()
        {
            //Formatter = exception => JsonConvert.SerializeObject(new
            //{
            //    error = new
            //    {
            //        exception = exception.GetType().Name,
            //        message = exception.Message
            //    }
            //});
        }
    }
josephwoodward commented 6 years ago

Thanks for raising this, I'll take a look at it.

josephwoodward commented 6 years ago

This has been fixed in the latest version which I'm hoping to release tomorrow, thanks for reporting it!

pnevill commented 6 years ago

Thanks, the new version is working well!

josephwoodward commented 6 years ago

Great! Thanks for reporting the issue in the first place :) I've also added a logging endpoint too.

pnevill commented 6 years ago

Already started using the new logging endpoint that you added - great addition. Thanks again.