Tôi đã đi kèm với một phần mở rộng nhỏ khi tôi nhanh chóng muốn thử/bắt mỗi lần lặp của một IEnumerable<T>
Cách sử dụng
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();
}
Việc gia hạn
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; }
}
}
Chúng tôi cuối cùng có thể đi một chút nữa bởi có một phần mở rộng SkipOnException
, chấp nhận tùy chọn một trình xử lý ngoại lệ ví dụ.
Bạn cho rằng lạm dụng ngoại lệ là gì? Trong logic kinh doanh của tôi, tôi có một phương pháp để tính lương của nhân viên. Có nhiều thứ khác nhau có thể sai lầm như người lao động không có lương. Tôi đã thực hiện một ngoại lệ tùy chỉnh tôi có thể ném và bắt trong bộ điều khiển của tôi và đưa vào mô hình xem của tôi. Thật tồi tệ? – Pluc
@Pluc: Nhân viên * có nghĩa là * để có một bộ lương không? Nếu vậy, nó thiếu âm thanh đặc biệt. Nếu nó có phần dự kiến, tôi có lẽ sẽ không sử dụng ngoại lệ để xử lý nó. –