3

我目前正在与 Personio 集成以获取员工数据。

下面的解决方案没有等待响应,而是在代码中注释的位置突然跳出了第二种方法:

using Personio.Client.Configuration;
using Personio.Client.Exceptions;
using Personio.Client.Models.Data;
using LanguageExt;
using Newtonsoft.Json;
using RestSharp;

namespace Enpal.Personio.Client;

public class PersonioCompanyEmployeesClient
{
    private readonly PersonioAuthorizationClient _authorizationClient;
    private readonly PersonioConfig _personioConfig;
    private readonly RestClient _restClient;

    public PersonioCompanyEmployeesClient(PersonioAuthorizationClient authorizationClient, PersonioConfig personioConfig, RestClient restClient)
    {
        _authorizationClient = authorizationClient;
        _personioConfig = personioConfig;
        _restClient = restClient;
    }

    public TryAsync<List<Record>> TryGet(EmployeeRequestOptions options) =>
        _authorizationClient.WithAuthorization<List<Record>>(token =>
        {
            _restClient.BaseUrl = new Uri(_personioConfig.BaseUrl, "/v1/company/employees");
            _restClient.Timeout = -1;

            IRestRequest request = new RestRequest(Method.GET)
                .AddQueryParameter("limit", options.MaximumRecordCount.ToString())
                .AddQueryParameter("offset", options.PageOffset.ToString())
                .AddHeader("Accept", "application/json")
                .AddHeader("Authorization", $"Bearer {token.Value}");

            return GetRecordsAsync(request);
        });

    private async Task<List<Record>> GetRecordsAsync(IRestRequest request)
    {
        IRestResponse<RecordRequestResponse> requestResponse = await _restClient.ExecuteAsync<RecordRequestResponse>(request);
        // Nothing below this line is ever executed!
        if (requestResponse.IsSuccessful)
        {
            RecordRequestResponse? employeesResponse = JsonConvert.DeserializeObject<RecordRequestResponse>(requestResponse.Content);
            return (employeesResponse != null && employeesResponse.WasSuccessful)
                ? employeesResponse.Records
                    .ToList()
                : throw new PersonioRequestException("Connected to Personio, but could not get records.");
        }
        else
        {
            throw (requestResponse.ErrorException != null)
                ? new PersonioRequestException("Could not get records from Personio.", requestResponse.ErrorException)
                : new PersonioRequestException("Could not get records from Personio.  Reason unknown.");
        }
    }
}

但是,我可以使用同步方法使这个解决方案工作,如下所示:

public TryAsync<List<Record>> TryGet(EmployeeRequestOptions options) =>
        _authorizationClient.WithAuthorization<List<Record>>(token =>
        {
            _restClient.BaseUrl = new Uri(_personioConfig.BaseUrl, "/v1/company/employees");
            _restClient.Timeout = -1;

            IRestRequest request = new RestRequest(Method.GET)
                .AddQueryParameter("limit", options.MaximumRecordCount.ToString())
                .AddQueryParameter("offset", options.PageOffset.ToString())
                .AddHeader("Accept", "application/json")
                .AddHeader("Authorization", $"Bearer {token.Value}");

            return GetRecordsAsync(request);
        });

    private async Task<List<Record>> GetRecordsAsync(IRestRequest request)
    {
        IRestResponse<RecordRequestResponse> requestResponse = await _restClient.ExecuteAsync<RecordRequestResponse>(request);
        if (requestResponse.IsSuccessful)
        {
            RecordRequestResponse? employeesResponse = JsonConvert.DeserializeObject<RecordRequestResponse>(requestResponse.Content);
            return (employeesResponse != null && employeesResponse.WasSuccessful)
                ? employeesResponse.Records
                    .ToList()
                : throw new PersonioRequestException("Connected to Personio, but could not get records.");
        }
        else
        {
            throw (requestResponse.ErrorException != null)
                ? new PersonioRequestException("Could not get records from Personio.", requestResponse.ErrorException)
                : new PersonioRequestException("Could not get records from Personio.  Reason unknown.");
        }
    }

唯一的变化:

  1. GetRecords()使用Execute而不是ExecuteAsync
  2. GetRecords()返回List<Record>而不是Task<List<Record>>
  3. TryGet()GetRecordsAsync(request)Task.FromResult()返回之前包裹。
4

2 回答 2

1

查看 restsharp 的文档后,ExecuteAsync不会抛出异常,而是填充response.ErrorExceptionresponse.ErrorMessage如果response.IsSuccessful等于 false,那么您应该首先检查response.IsSuccessful属性值。

更多细节可以在这里找到 - https://restsharp.dev/intro.html#content-type

于 2021-12-16T16:08:02.977 回答
0

我必须补充一点,在上一个版本之前,RestSharp 的异步请求都很混乱。您可以快速了解如何HttpWebRequest处理异步调用,以及 RestSharp 为管理它们做了什么,这是核心。我知道它对某些人有用,但肯定存在问题。

如果它仍然与您相关,我建议您移至 v107。您使用的那些界面已经消失,不确定对您来说有多大的问题。但所有同步方法也都消失了,现在完全异步了,而且可以正常工作。

于 2022-01-14T15:42:03.217 回答