C#自定義異常 統一異常處理


異常類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasErpQuerySys.EasApplication
{
    [Serializable]
    public class EasWebServiceException : ApplicationException
    {
        private readonly ExceptionResult _exceptionResult;
        public EasWebServiceException() { }
        public EasWebServiceException(string resultStatus, string resultMsg) : base(resultStatus)
        {
            _exceptionResult = new ExceptionResult { resultMsg = resultMsg, resultStatus = resultStatus };
        }
        public ExceptionResult GetExceptionResult()
        {
            return _exceptionResult;
        }
    }
    public class ExceptionResult
    {
        public string resultStatus { get; set; }
        public string resultMsg { get; set; }
    }
}

觸發類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasErpQuerySys.EasApplication
{
    public class EasAppService : IEasAppService
    {
        public string Test()
        {

            throw new EasWebServiceException("失敗", "失敗了滾蛋");

        }
    }
}

捕獲類

using EasErpQuerySys.EasApplication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            IEasAppService easAppService = new EasAppService();


            try
            {
                easAppService.Test();
            }
            catch (EasWebServiceException e)
            {
                var tt = e.GetExceptionResult();
                Console.WriteLine(tt.resultMsg);
                Console.WriteLine(tt.resultStatus);
                Console.ReadLine();
            }
        }
    }
}

輸出結果:

 


免責聲明!

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



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