NET问答:在 Linq 查询中可以处理异常吗?
生活随笔
收集整理的這篇文章主要介紹了
NET问答:在 Linq 查询中可以处理异常吗?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
Jader Dias:
先上例子:
myEnumerable.Select(a?=>?ThisMethodMayThrowExceptions(a));如何讓上面的 Linq查詢 即使在拋出異常的情況下也能完整的執行,就像那種帶有默認值的 try...catch 一樣,當異常拋出時總會執行 catch 后再把它救回來。
回答區
Stefan Steinegger:
本質上來說,上面這段代碼大體上能解決你的問題,但有一些壞味道。
LeBaptiste:
我自己寫了一些 擴展方法 可以捕獲 IEnumerable<T> 中每一個迭代項的異常。
用法
public?void?Test() {List<string>?completedProcesses?=?initialEnumerable.SelectTry(x?=>?RiskyOperation(x)).OnCaughtException(exception?=>?{?_logger.Error(exception);?return?null;?}).Where(x?=>?x?!=?null)?//?filter?the?ones?which?failed.ToList(); }擴展方法
public?static?class?OnCaughtExceptionExtension {public?static?IEnumerable<SelectTryResult<TSource,?TResult>>?SelectTry<TSource,?TResult>(this?IEnumerable<TSource>?enumerable,?Func<TSource,?TResult>?selector){foreach?(TSource?element?in?enumerable){SelectTryResult<TSource,?TResult>?returnedValue;try{returnedValue?=?new?SelectTryResult<TSource,?TResult>(element,?selector(element),?null);}catch?(Exception?ex){returnedValue?=?new?SelectTryResult<TSource,?TResult>(element,?default(TResult),?ex);}yield?return?returnedValue;}}public?static?IEnumerable<TResult>?OnCaughtException<TSource,?TResult>(this?IEnumerable<SelectTryResult<TSource,?TResult>>?enumerable,?Func<Exception,?TResult>?exceptionHandler){return?enumerable.Select(x?=>?x.CaughtException?==?null???x.Result?:?exceptionHandler(x.CaughtException));}public?static?IEnumerable<TResult>?OnCaughtException<TSource,?TResult>(this?IEnumerable<SelectTryResult<TSource,?TResult>>?enumerable,?Func<TSource,?Exception,?TResult>?exceptionHandler){return?enumerable.Select(x?=>?x.CaughtException?==?null???x.Result?:?exceptionHandler(x.Source,?x.CaughtException));}public?class?SelectTryResult<TSource,TResult>{internal?SelectTryResult(TSource?source,?TResult?result,?Exception?exception){Source?=?source;Result?=?result;CaughtException?=?exception;}public?TSource?Source?{?get;?private?set;?}public?TResult?Result?{?get;?private?set;?}public?Exception?CaughtException?{?get;?private?set;?}} }如果還想完美一點,可以再實現一個 SkipOnException, 接收可以忽略的異常。
點評區
回答區的兩個答案,第一種方法簡單粗暴,但各位也能體會出這種寫法的生硬之處,第二種寫法就比較????????了,讓我想起了強大的 Polly (基于.NET的彈性及瞬態故障處理庫),各種眼花繚亂的玩法,大家有興趣可以看一看: https://github.com/App-vNext/Polly
原文鏈接:https://stackoverflow.com/questions/1294251/is-it-possible-to-handle-exceptions-within-linq-queries
總結
以上是生活随笔為你收集整理的NET问答:在 Linq 查询中可以处理异常吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Core中间件初始化探究
- 下一篇: MIPS投RISC-V是龙芯新征程的开始