Web API 实战之 异常处理

using Ahoo.Demo.Framework;
using Ahoo.Demo.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Properties;

namespace Ahoo.Demo.WebAPI.Filter
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ExceptionAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //这里可以加入Log部分,记录异常日志

            ResponseMessage resp = new ResponseMessage
            {
                IsSuccess = false,
                ErrorCode = "0001",
                Message = actionExecutedContext.Exception.Message
            };
            if (actionExecutedContext.Exception is MEException)
            {
                MEException meEx = actionExecutedContext.Exception as MEException;
                resp.ErrorCode = meEx.ErrorCode;
            }

            actionExecutedContext.Response = actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(resp);
            base.OnException(actionExecutedContext);
        }
    }
}

使用部分:
在Global 注册异常筛选器:

GlobalConfiguration.Configuration.Filters.Add(new ExceptionAttribute());

你可能感兴趣的:(web-api)