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

时间:2013-03-25 21:40:10

标签: c# facebook exception

我正在创建一个实用程序类,它将在我的Facebook应用程序中用于常用的任务,例如从URL检索Facebook页面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;
    }
}

程序类,只是测试: - 注意“输入”和“输出”只是文本框。

    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.";
            }
        }
    }

从实用程序类中重新抛出异常是否正确,以便调用类可以捕获它并执行需要执行的操作?

2 个答案:

答案 0 :(得分:2)

似乎你对捕获的异常没有任何作用 - 所以不要抓住它们。有很多关于异常处理的讨论,但一般来说,当你与它们有关时,你应该捕获异常,或者至少最后使用清理资源。

答案 1 :(得分:1)

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

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方法中看起来不像你,所以你应该只传播它们。

相关问题