在实用程序类中抛出异常的最佳实践

本文关键字:最佳 抛出异常 实用程序 | 更新日期: 2023-09-27 18:06:02

我正在创建一个实用程序类,它将在我的Facebook应用程序中用于通常完成的任务,例如从URL检索Facebook Page ID。我不确定下面的代码是否是抛出和捕获异常的正确方法。谁能告诉我,谢谢。

实用工具类:

public static class FacebookUtilities
{ 
    public static string GetPageIDFromGraph(string pageUri, string accessToken)
    {
        try
        {
            FacebookClient client = new FacebookClient(accessToken);
            dynamic result = client.Get(GetPageIDFromUri(pageUri), new { fields = "id" });
            return result.ToString();
        }
        catch (FacebookOAuthException)
        {
            throw;
        }
        catch (FacebookApiException)
        {
            throw;
        }
    }
    public static string GetPageIDFromUri(string pageUri)
    {
        if (pageUri.Contains('/'))
            pageUri = pageUri.Substring(pageUri.LastIndexOf('/') + 1);
        if (pageUri.Contains('?'))
            return pageUri.Substring(0, pageUri.IndexOf('?'));
        else
            return pageUri;
    }
}

程序类,只是测试:-"输入"answers"输出"只是文本框。

    private void btnGetPageID_Click(object sender, EventArgs e)
    {
        try
        {
            output.Text = FacebookUtilities.GetPageIDFromGraph(input.Text, "Some Access Token Goes Here");
        }
        catch (FacebookOAuthException ex)
        {
            if (ex.ErrorCode == 803)
            {
                output.Text = "This page does not exist";
            }
        }
        catch (FacebookApiException ex)
        {
            if (ex.ErrorCode == 100)
            {
                output.Text = "The request was not supported. The most likely cause for this is supplying an empty page ID.";
            }
        }
    }

简单地从实用程序类中重新抛出异常以便调用类可以捕获它并做需要做的事情是正确的吗?

在实用程序类中抛出异常的最佳实践

似乎你对捕获的异常什么都不做-所以不要捕获它们。有很多关于异常处理的讨论,但一般来说,您应该在与异常有关时捕获异常,或者至少使用finally来清理资源。

由于您没有以任何方式处理异常,因此您的代码可以只是:

public static string GetPageIDFromGraph(string pageUri, string accessToken)
{
    FacebookClient client = new FacebookClient(accessToken);
    dynamic result = client.Get(GetPageIDFromUri(pageUri), new { fields = "id" });
    return result.ToString();
}

你应该只捕捉异常,当你可以有意义地处理它们,它看起来不像你可以在你的GetPageIDFromGraph方法,所以你应该只是传播它们。