我有一个Web-API,其中有许多函数可以将对象作为JSON返回,例如:
MyPython.py
如何实现错误处理?如果发生错误,我想返回一个JSON,只是说{"错误":"出错了"}
现在,如果发生崩溃,API只会返回500错误。
答案 0 :(得分:2)
您最好的选择是实施自定义ExceptionHandler
public class MyCustomExceptionHandler : ExceptionHandler
{
private readonly HttpConfiguration _configuration;
public MyCustomExceptionHandler(HttpConfiguration config){
_configuration = config;
}
public override void Handle(ExceptionHandlerContext context)
{
var formatters = _configuration.Formatters;
var negotiator = _configuration.Services.GetContentNegotiator();
context.Result = new NegotiatedContentResult<ErrorResponse>(HttpStatusCode.InternalServerError, new ErrorResponse
{
Message = context.Exception.Message,
CustomProperty = "Something"
}, negotiator, context.Request, formatters);
}
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true; //your logic if you want only certain exception to be handled
}
}
internal class ErrorResponse
{
public string Message { get; set; }
public string CustomProperty { get; set; }
}
并在WebApiConfig.cs
文件中注册:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Services.Replace(typeof (IExceptionHandler), new MyCustomExceptionHandler(config));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
通过这种方式,您可以在未处理的异常情况下返回错误消息的精细分级自定义。