【问题标题】:How to correctly catch and handle errors in Http get request to Facebook api如何正确捕获和处理对 Facebook api 的 Http 获取请求中的错误
【发布时间】:2021-12-13 09:36:46
【问题描述】:

我正在尝试使用从 Facebook 接收到的代码从 Facebook 的图形 API 接收访问令牌。这是我第一次在 .NET CORE 中使用 API。代码似乎工作正常,但我不确定我是否以正确的方式处理响应和捕获异常。虽然我可以用 TRY CATCH 还是觉得不是很舒服。我想让这个方法尽可能的健壮。

非常感谢您的帮助。

处理类

public class FacebookService : IFacebookService
{
        private readonly HttpClient _httpClient;
        private readonly IConfiguration configuration;

        public FacebookService(HttpClient httpClient, IConfiguration iConfig)
        {
            _httpClient = httpClient;
            configuration = iConfig;
        }

        public async Task<string> GetShortLiveToken(string code)
        {
            try
            {
                string appId = configuration.GetSection("FacebookApp").GetSection("AppID").Value;
                string appSecret = configuration.GetSection("FacebookApp").GetSection("AppSecret").Value;
                var getTokenUri = $"oauth/access_token?client_id={appId}&client_secret={appSecret}&code={code}&redirect_uri=https://localhost:44373/Home/HandleFbAccess";
                var response = await _httpClient.GetAsync(getTokenUri);
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    return response.ReasonPhrase;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }

        public async Task<string> GetLongLiveToken(string shortlivedtoken)
        {
            throw new NotImplementedException();
        }

}

调用方法

public async Task<IActionResult> HandleFbAccess(string code, string granted_scopes)
{
    try
    {
        var result = await _facebookService.GetShortLiveToken(code);
        // more things to do here
        //.....
        return View("Index");

    }
    catch(Exception ex)
    {
        throw ex;
    }
    
}

【问题讨论】:

  • 仅供参考:throw ex; 几乎不是您想要使用的东西。此外,使用 try-catch 只是为了重新抛出而没有任何逻辑(甚至没有记录!)是没有意义的,只需完全删除 try-catch。但是,Controller 操作不应引发异常,而应返回内部服务器错误
  • 对我来说,你的代码只做了一个发送http请求和接收响应的过程,不用担心是否发生异常以及如何处理,你可以关注@987654324 @ 本身。

标签: c# facebook asp.net-core dotnet-httpclient


【解决方案1】:

try{}catch(Exception ex){}在你的代码突然出现异常时起作用,比如nullpointexception,但是你现在担心httpclient send request,你应该知道这个方法只能抛出这些异常,所有这些异常都与脸书 api。

我对您的方案的想法是在这里继续使用try catch,但是您需要根据catch{}中的异常类型设置操作并在此处编写自定义逻辑代码,以处理诸如404,400,503问题等http响应:

if (response.IsSuccessStatusCode){
     return await response.Content.ReadAsStringAsync();
}else{
    return response.ReasonPhrase;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 2022-08-24
    • 2016-05-29
    • 2020-11-16
    • 2012-05-15
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多