zoukankan      html  css  js  c++  java
  • .netcore 简单封装全局异常捕获

    using Common;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using SMS_Platform.Model.Response;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    
    /// <summary>
    /// 暂时简单封装大型项目用elk efk替代
    /// </summary>
    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate next;
    
        public ErrorHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex); // 日志记录
                var statusCode = context.Response.StatusCode;
                if (ex is ArgumentException)
                {
                    statusCode = 200;
                }
                await HandleExceptionAsync(context, statusCode, ex.Message);
            }
            finally
            {
                var statusCode = context.Response.StatusCode;
                var msg = "";
                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);
                }
            }
        }
    
        /// <summary>
        /// 对象转为Xml
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private static string Object2XmlString(object o)
        {
            StringWriter sw = new StringWriter();
            try
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());
                serializer.Serialize(sw, o);
            }
            catch
            {
            }
            finally
            {
                sw.Dispose();
            }
            return sw.ToString();
        }
    
        private static async Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
        {
            var data = DataResponse.AsError(SMS_Platform.Model.Enums.EnumCode.Invalid_Service_Data, msg);
            var result = JsonConvert.SerializeObject(data);
            if (context.Response?.ContentType?.ToLower() == "application/xml")
            {
                await context.Response.WriteAsync(Object2XmlString(data)).ConfigureAwait(false);
            }
            else
            {
                context.Response.ContentType = "application/json;charset=utf-8";
                await context.Response.WriteAsync(result).ConfigureAwait(false);
            }
        }
    }
    
    public static class ErrorHandlingExtensions
    {
        public static IApplicationBuilder UseErrorHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ErrorHandlingMiddleware>();
        }
    }
         app.UseErrorHandler();
  • 相关阅读:
    12.7 Test
    51Nod.1766.树上最远点对(树的直径 RMQ 线段树/ST表)
    BZOJ.3675.[APIO2014]序列分割(DP 斜率优化)
    BZOJ.4515.[SDOI2016]游戏(树链剖分 李超线段树)
    BZOJ.3165.[HEOI2013]Segment(李超线段树)
    Linux系统CentOS进入单用户模式和救援模式详解
    KVM 管理界面挂载多UKEY
    挂载银行前置机Ukey到windows server2012虚拟机的操作记录
    为什么服务器做了raid 系统文件还会丢失?
    LVS+Keepalived深度理解,阐述你不知道的坑点
  • 原文地址:https://www.cnblogs.com/chongyao/p/12212821.html
Copyright © 2011-2022 走看看