I have a simple REST client written using RestSharp.
var opts = new RestClientOptions("http://api.muyservice.com/"){ // ResponseStatus should not be an Error when deserialisation failed. FailOnDeserializationError = false,};using var client = new RestClient(opts);var request = new RestRequest("myEndpoint");var response = await client.ExecuteAsync<ResponseDto>(request);// error handling// network error? No, not really.// Also an http codes 4xx/5xx, except 404if (response.ResponseStatus != ResponseStatus.Completed) { // log network errors}else if (response.StatusCode != HttpStatusCode.OK){ // http request completed successfully, but server returned non-200 results. // handle server errors if (response.StatusCode == HttpStatusCode.BadRequest) { // extract error details from response body } else { // handle generic server error }}else if (response.Data == null){ // serialization failed}else{ // all ok, handle the results}I want to handle network/server/serialisation errors in the different ways (e.g. log different details, suggest to adjust timeouts in the config in case of request timeout and so on), but I have not found the straightforward way to distinguish between the error types (network/server/deserialisation) and make the granular error handling.
What problems I found so far:
- the
response.ResponseStatuswill beErrorin case of network error or in case of server errors 5xx/4xx (except 404). - in case of a timeout the
ResponseStatuswill beTimedOut, but theErrorMessageand theErrorExceptionwill beOperation was canceled(no single word about the timeout) IsSuccessfulStatusCodewill saySuccessfor http 404 code.- there is no dedicated error state for the deserialisation (which is understandable because different deserialisers can be used). So if
nullis the valid value for theResponseDto, then there is no way to diagnose deserialisation errors at all?
Is there is a straightforward way to handle the error in RestSharp in a granular way?