I copied and cleared the corresponding code a bit.
var request = new HttpRequestMessage(HttpMethod.Post, requestUrl); var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); using (var httpStream = await response.Content.ReadAsStreamAsync()) { var timestampedName = FormatTimestampedString(symbol, true); var filePath = Path.Combine(outputDirectory, timestampedName + ".csv"); using (var fileStream = File.Create(filePath)) { await httpStream.CopyToAsync(fileStream); } }
The question is, what if something goes wrong while reading a stream and copying it to a file?
All logical errors have already been considered as part of the HTTP request and response cycle: the server received your request, it decided that it is valid, it responded successfully (part of the response header), and now it has sent you the result (part of the response body).
The only errors that may occur right now are things like a server crash, loss of connection, etc. I understand that they will display as HttpRequestException , that is, you can write code like this:
try { using (var httpStream = await response.Content.ReadAsStreamAsync()) { var timestampedName = FormatTimestampedString(symbol, true); var filePath = Path.Combine(outputDirectory, timestampedName + ".csv"); using (var fileStream = File.Create(filePath)) { await httpStream.CopyToAsync(fileStream); } } } catch (HttpRequestException e) { ... }
The documentation says little, unfortunately. The source of the link is wrong. So, your best bet is to start from there and possibly log all exceptions that are not HttpRequestException if there is another type of exception that can be thrown while loading the response body.
source share