Error handling (Sending ex.Message to the client)

后端 未结 6 2032
野趣味
野趣味 2020-11-29 20:38

I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors ou

6条回答
  •  余生分开走
    2020-11-29 21:12

    Here is an simple error DTO class

    public class ErrorDto
    {
        public int Code {get;set;}
        public string Message { get; set; }
    
        // other fields
    
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
    

    And then using the ExceptionHandler middleware:

                app.UseExceptionHandler(errorApp =>
                {
                    errorApp.Run(async context =>
                    {
                        context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
                        context.Response.ContentType = "application/json";
    
                        var error = context.Features.Get();
                        if (error != null)
                        {
                            var ex = error.Error;
    
                            await context.Response.WriteAsync(new ErrorDto()
                            {
                                Code = ,
                                Message = ex.Message // or your custom message
                                // other custom data
                            }.ToString(), Encoding.UTF8);
                        }
                    });
                });
    

提交回复
热议问题