C#-引发异常的最佳方法
作者:互联网
您是否知道以下引发异常的更好方法(更漂亮)?
public long GetPlaylistId(long songInPlaylistId)
{
var songInPlaylist = service.GetById(songInPlaylistId);
return songInPlaylist
.With(x => x.Playlist)
.ReturnValueOrException(x => x.Id,
new ArgumentException(
"Bad argument 'songInPlaylistId'"));
}
单声道扩展方法:
public static TResult With<TInput, TResult>(this TInput obj,
Func<TInput, TResult> evaluator)
where TInput : class
where TResult : class
{
return obj == null ? null : evaluator(obj);
}
public static TResult ReturnValueOrException<TInput, TResult>(
this TInput obj, Func<TInput, TResult> evaluator, Exception exception)
where TInput : class
{
if (obj != null)
{
return evaluator(obj);
}
throw exception;
}
解决方法:
如果尝试获取没有播放列表的内容的播放列表是有效的,则您不应引发异常,而应返回一个表示“未找到”的特殊值(例如,0或-1取决于播放列表ID的工作方式).
或者,您可以编写一个TryGetPlaylistId()方法,该方法的工作方式类似于Microsoft的TryXXX()方法(例如SortedList.TryGetValue()
),例如:
public bool TryGetPlaylistId(long songInPlaylistId, out long result)
{
result = 0;
var songInPlaylist = service.GetById(songInPlaylistId);
if (songInPlaylist == null)
return false;
if (songInPlaylist.Playlist == null)
return false;
result = songInPlaylist.Playlist.Id;
return true;
}
这种方法的一个小问题是,您在尝试诊断问题时会掩盖可能有用的信息.也许添加Debug.WriteLine()或其他某种形式的日志记录将很有用.关键是,您无法区分找不到播放列表ID的情况和找到但不包含播放列表的情况.
否则,您可能会抛出一个异常,该异常具有更多信息,例如:
public long GetPlaylistId(long songInPlaylistId)
{
var songInPlaylist = service.GetById(songInPlaylistId);
if (songInPlaylist == null)
throw new InvalidOperationException("songInPlaylistId not found: " + songInPlaylistId);
if (songInPlaylist.Playlist == null)
throw new InvalidOperationException("Playlist for ID " + songInPlaylistId " has no playlist: ");
return songInPlaylist.Playlist.Id;
}
在播放列表中找不到歌曲可能是有效的情况,但在没有播放列表的情况下找到歌曲是无效的,在这种情况下,您将在第一种情况下返回一个特殊值并引发异常在第二种情况下,例如:
public long GetPlaylistId(long songInPlaylistId)
{
var songInPlaylist = service.GetById(songInPlaylistId);
if (songInPlaylist == null)
return -1; // -1 means "playlist not found".
if (songInPlaylist.Playlist == null)
throw new InvalidOperationException("Playlist for ID " + songInPlaylistId " has no playlist: ");
return songInPlaylist.Playlist.Id;
}
无论如何,我个人认为您的扩展方法只是使代码模糊.
标签:monads,exception,null,c 来源: https://codeday.me/bug/20191121/2055097.html