c# - Getting response body on failed request with HttpRequestException -
i trying log failed requests httprequestexception.
my server returns error code and additional json payload @ response body. need access json. how read response body in case of errored request? know actual response not null. it's api , confirm returns json payload 4xx status codes, giving detailed insight error.
how access it? here code:
using (var httpclient = new httpclient()) { try { string resultstring = await httpclient.getstringasync(endpoint); var result = jsonconvert.deserializeobject<...>(resultstring); return result; } catch (httprequestexception ex) { throw ex; } } i trying data in throw ex line, couldn't find way.
exactly @frédéric suggested, if use getasync method you'll proper httpresponsemessage object give more information response. details when error occurs can desearlize errors exception or custom exception object response content below:
public static exception createexceptionfromresponseerrors(httpresponsemessage response) { var httperrorobject = response.content.readasstringasync().result; // create anonymous object use template deserialization: var anonymouserrorobject = new { message = "", modelstate = new dictionary<string, string[]>() }; // deserialize: var deserializederrorobject = jsonconvert.deserializeanonymoustype(httperrorobject, anonymouserrorobject); // wrap exception best fullfills needs of application: var ex = new exception(); // sometimes, there may model errors: if (deserializederrorobject.modelstate != null) { var errors = deserializederrorobject.modelstate .select(kvp => string.join(". ", kvp.value)); (int = 0; < errors.count(); i++) { // wrap errors base exception.data dictionary: ex.data.add(i, errors.elementat(i)); } } // othertimes, there may not model errors: else { var error = jsonconvert.deserializeobject<dictionary<string, string>>(httperrorobject); foreach (var kvp in error) { // wrap errors base exception.data dictionary: ex.data.add(kvp.key, kvp.value); } } return ex; } usage:
using (var client = new httpclient()) { var response = await client.getasync("http://localhost:51137/api/account/register"); if (!response.issuccessstatuscode) { // unwrap response , throw api exception: var ex = createexceptionfromresponseerrors(response); throw ex; } } here's source article detailing more handling httpresponsemessage , it's content.
Comments
Post a Comment