WebAPI 操作返回

強悍的抽屜發表於2016-05-03

定義了一個返回列舉:

    public enum ResultExceptionEnum
    {
        積分不足       = 4002,
        支付失敗       = 4003,
        使用者不存在     = 4004,
        驗證碼傳送失敗 = 4005,
        驗證碼不正確   = 4006,
        賬號已存在     = 4007,
        暱稱已存在     = 4008,

        公會不存在     = 4100,
        公會名稱已存在 = 4101,
        使用者不在此公會 = 4102,

        社群不存在     = 4200,
        社群名稱已存在 = 4201,
    }

 

定義一個返回 Exception

    public class ResultException : Exception
    {
        public ResultException(){}

        public ResultException(int code, string msg)
        {
            Code = code;
            Msg = msg;
        }

        public ResultException(ResultExceptionEnum code)
        {
            Code = code.GetHashCode();
            Msg = Enum.GetName(typeof(ResultExceptionEnum), code);
        }

        public int Code { get; set; }

        public string Msg { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(new { code = Code, msg = Msg });
        }

        public object ToResult()
        {
            var obj = new { code = Code, msg = Msg };
            return obj;
        }
    }

 

 

刪除操作返回:

        // DELETE: api/Values/5
        public IHttpActionResult Delete(int id)
        {

            try
            {
                throw new ResultException(ResultExceptionEnum.驗證碼不正確);
            }
            catch (ResultException ex)
            {
                return Ok(ex.ToResult());
            }
            //return Ok(new { code = 200, msg = "刪除成功" });
        }

 

上面兩個風格,

1.  丟擲異常,返回。

2. 直接返回

 

結果:

 

再來個異常版:

        // DELETE: api/Values/5
        public IHttpActionResult Delete(int id)
        {
            //try
            //{
            //    throw new ResultException(ResultExceptionEnum.驗證碼不正確);
            //}
            //catch (ResultException ex)
            //{
            //    return Ok(ex.ToResult());
            //}
            //return Ok(new { code = 200, msg = "刪除成功" });

            throw new ResultException(ResultExceptionEnum.驗證碼不正確);
        }

 

配置下:

WebApiConfig

config.Filters.Add(new WebApiExceptionFilter());

    /// <summary>
    /// 全域性API異常
    /// </summary>
    public class WebApiExceptionFilter : ExceptionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var ex = context.Exception;
            if(ex is ResultException)
            {
                var ex2 = (ResultException)ex;
                context.Response = context.Request.CreateResponse(ex2.ToResult());
            }
            base.OnException(context);
        }
    }

 

只是這樣拋異常 對效能有影響嗎?

相關文章