在我的 Web 服务中,我覆盖了 ExceptionHandler,但我不清楚如何格式化异常以符合 OData 错误标准。也许我的做法是错误的,因为我在网上找不到任何示例。
根据我的理解,web api 2 有一个全局异常处理的概念,您可以使用自定义的 ExceptionHandler 来处理服务中抛出的任何异常。异常仍应使用新的 IHttpActionResult() 更新 ExceptionContext.Result。如何将输入到 IHttpActionResult 的数据格式化为 OData 错误。
下面是 ExceptionHandler 的一个片段,我一直在思考如何使用正确的 OData HttpResponse 消息覆盖 context.Result。
public class CustomExceptionHandler: ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
HttpResponseMessage msg = context.Request.CreateErrorResponse(HttpStatusCode.NotFound, new ODataError
{
ErrorCode = context.Exception.Message,
Message = context.Exception.InnerException.Message,
InnerError = new ODataInnerError
{
Message = context.Exception.InnerException.Message
}
});
context.Result = //How do you wrap the OData HttpResponseMessage into a IHttpActionResult
}
}
任何建议表示赞赏,
谢谢,
D
最佳答案
context.Result = new System.Web.Http.Results.ResponseMessageResult(msg);
关于exception-handling - OData Web Api 2 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34169766/