Error handling (Sending ex.Message to the client)

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

    You can create a custom Exception Filter like below

    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var exception = context.Exception;
            context.Result = new JsonResult(exception.Message);
        }
    }
    

    Then apply the above attribute to your controller.

    [Route("api/[controller]")]
    [CustomExceptionFilter]
    public class ValuesController : Controller
    {
         // GET: api/values
        [HttpGet]
        public IEnumerable Get()
        {
            throw new Exception("Suckers");
            return new string[] { "value1", "value2" };
        }
    }
    

提交回复
热议问题