Beispiel #1
0
        public async Task Invoke(HHttpContext context)
        {
            string language = context.Request.Headers["Accept-Language"];

            if (string.IsNullOrEmpty(language))
            {
                language = "zh-Hans";
            }
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.StackTrace);
                //this.GetLogger().Error(string.Format("全局异常中间件捕捉:{0}\r\n详细错误:\r\n{1}", ex.Message, ex));
                var dict       = MyExceptionUtil.GetFriendlyMessage(ex, language);
                var statusCode = context.Response.StatusCode;
                if (ex is ArgumentException || ex is MyException)
                {
                    statusCode = 200;
                }
                await HandleExceptionAsync(context, statusCode, dict["message"]);
            }
            finally
            {
                var statusCode = context.Response.StatusCode;
                var msg        = EnumHelper.GetDescription(statusCode, typeof(MyHttpStatusCode), language);
                //401 未授权
                //if (statusCode == 401)
                //{
                //    msg =  "未授权";
                //}
                //else if (statusCode == 404)
                //{
                //    msg = "未找到服务";
                //}
                //else if (statusCode == 502)
                //{
                //    msg = "请求错误";
                //}
                //else if (statusCode != 200)
                //{
                //    msg = "未知错误";
                //}
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await HandleExceptionAsync(context, statusCode, msg);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// 根据异常构建返回
        /// </summary>
        /// <param name="e">异常</param>
        /// <returns></returns>
        public static JsonResult ApiResult(Exception e, string language = "zh-Hans")
        {
            if (e is MyException)
            {
                var me = (MyException)e;
                return(ApiResult <string>(null, new MyErrorInfo {
                    Code = me.Code,
                    Message = me.Message,
                    SubMessage = me.SubMessage,
                    SubCode = me.SubCode
                }));
            }

            //解析错误得到字典
            var errorDict = MyExceptionUtil.GetFriendlyMessage(e, language);

            return(ApiResult <string>(null,
                                      new MyErrorInfo
            {
                Code = errorDict["code"],
                Message = errorDict["message"]
            }
                                      ));
        }