Error handling (Sending ex.Message to the client)

后端 未结 6 2025
野趣味
野趣味 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

    Yes it is possible to change the status code to whatever you need:

    In your CustomExceptionFilterAttribute.cs file modify the code as follows:

    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var exception = context.Exception;
            context.Result = new ContentResult
            {
                Content = $"Error: {exception.Message}",
                ContentType = "text/plain",
                // change to whatever status code you want to send out
                StatusCode = (int?)HttpStatusCode.BadRequest 
            };
        }
    }
    

    That's pretty much it.

    If you have custom exceptions, then you can also check for them when grabbing the thrown exception from the context. Following on from that you can then send out different HTTP Status Codes depdending on what has happened in your code.

    Hope that helps.

提交回复
热议问题