问题描述
我想知道在ODataController中引发异常的最佳实践是什么.
I'm interested in knowing what are the best practices being followed to raise exceptions in the ODataController.
如果在方法中引发异常,则默认情况下会将其转换为响应代码500,并且内容中包含有关错误的详细信息.我想明确显示响应代码,并在密钥无效的情况下发送400.
If you raise an exception in the method it is translated to response code of 500 by default and the content has details on the error. I would like to be explicit of the response code and send 400 in cases of invalid key.
例如:如果输入请求的键无效,则希望返回HttpResponseCode 400,并且内容应具有类似于引发异常的错误详细信息.
For example: If the input request has an invalid key would like to return a HttpResponseCode of 400 and content should have the error details similar to raising an exception.
非常感谢您的投入
推荐答案
OData(至少从v3开始)使用特定的json 代表错误:
OData (at least since v3) uses specific json to represent errors:
{
"error": {
"code": "A custom error code",
"message": {
"lang": "en-us",
"value": "A custom long message for the user."
},
"innererror": {
"trace": [...],
"context": {...}
}
}
}
Microsoft .Net包含 Microsoft.Data.OData.ODataError 和 Microsoft.Data.OData.ODataInnerError 类在服务器端形成OData错误.
Microsoft .Net contains Microsoft.Data.OData.ODataError and Microsoft.Data.OData.ODataInnerError classes to form OData error on a server side.
形成适当的OData错误响应( HttpResponseMessage ),其中包含您可以执行的错误详细信息:
To form proper OData error response (HttpResponseMessage), that contains error details you can:
1)形成表单并使用 System.Web.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse 方法
1) form and return HttpResponseMessage in controller's action using System.Web.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse method
return Request.CreateErrorResponse(HttpStatusCode.Conflict, new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." }));
2)使用与创建HttpResponseMessage相同的方法抛出HttpResponseException
2) throw HttpResponseException using the same method for creating HttpResponseMessage
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." }));
3)抛出自定义类型的异常,并使用Web Api操作过滤器对其进行转换
3) throw custom typed exception and convert it using Web Api action filters
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is CustomException)
{
var e = (CustomException)context.Exception;
var response = context.Request.CreateErrorResponse(e.StatusCode, new ODataError
{
ErrorCode = e.StatusCodeString,
Message = e.Message,
MessageLanguage = e.MessageLanguage
});
context.Response = response;
}
else
base.OnException(context);
}
}
这篇关于ASP.NET Odata Web API的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!