.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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM