在ASP.NET webapi服务中,可以使用以下两种方式来处理错误:
public IHttpActionResult Get(int id)
{
var result = _service.GetById(id);
if (result == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return Ok(result);
}
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
{
var exceptionType = actionExecutedContext.Exception.GetType();
var errorMessage = "";
if (exceptionType == typeof(DivideByZeroException))
errorMessage = "不能进行0除。";
else if (exceptionType == typeof(FormatException))
errorMessage = "格式错误。";
else
errorMessage = "发生未知错误。";
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(errorMessage),
ReasonPhrase = "Error"
};
}
}
}
要在webapi中使用此自定义异常过滤器,可以在WebApiConfig类的Register方法中添加以下代码:
config.Filters.Add(new CustomExceptionFilter());
这样,当webapi发生异常时,会根据异常类型返回自定义的错误消息。