How can I properly send email (with error) from catch ()? - c#

I consume an API and now I want to handle possible errors in catch section. What I want to do now is to send email to given user when error is catched. My Email method works fine and sends mails properly. CallAPI method also works fine but when I add Email method to catch section then CallAPI method get highlighted with info that 'not all code paths return a value'. I can't return anything in catch except for sending an email. So how should I properly send email from catch?
CallAPI
private static async Task<T> CallAPI<T>(string endpoint, string accessToken)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Get,
new Uri(ApiUri, endpoint));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var _httpClient = new HttpClient();
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
var responseObject = await JsonSerializer.DeserializeAsync<T>(responseStream);
return responseObject;
}
catch (Exception e)
{
await Email(e);
}
}
Email
private static async Task Email(Exception e)
{
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("mail#mail.com");
message.To.Add(new MailAddress("mail#mail.com"));
message.Subject = "Test test";
message.IsBodyHtml = true;
message.Body = e.ToString();
smtp.Port = 25;
smtp.Host = "mail.yyy.com";
await smtp.SendMailAsync(message);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}

Returning default(T) might work for reference types but I don't suggest it for value types.
Say, if T is an int, default(T) results in 0, which might actually be an acceptable response.
There should be a more explicit way for the caller to distinguish if the call went in error or not.
With a custom object, such as ResponseBase<T>, you can easily detect that by a simple response.IsSuccess call.
public class ResponseBase<T> {
public bool IsSuccess { get; set; } = true;
public T Output { get; set; }
}
private static async Task<ResponseBase<T>> CallAPI<T>(string endpoint, string accessToken) {
var result = new ResponseBase<T>(); // Added this
try {
var request = new HttpRequestMessage(HttpMethod.Get,
new Uri(ApiUri, endpoint));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var _httpClient = new HttpClient();
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
var responseObject = await JsonSerializer.DeserializeAsync<T>(responseStream);
result.Output = responseObject; // Added this
}
catch (Exception e) {
await Email(e);
result.IsSuccess = false; // Added this
}
return result; // Added this
}

You didn't set the return result from your catch scope that you might return
generics type from Task<T>
One way you can try to return default(T)
catch (Exception e)
{
await Email(e);
return default(T);
}

Related

HttpClient.SendAsync() returns status code 200 even if the remote server is down

A simple login method that works just fine until I shut down my API. Then the try-catch block acts as intended, and an exception is thrown and caught but, _response comes out with a status code of "200, OK". For the love of me, I can't figure out why. Please help!
The code looks so bad mainly because of all the patching and testing I am doing on it to figure out what is happening.
HttpResponseMessage response = null;
public async Task<HttpResponseMessage> login(AuthModel model)
{
HttpResponseMessage response = null;
model.responseMessage = "";
var client = new HttpClient();
string text = "{\"email\": \""+model.email+"\",\"password\": \""+model.password+"\"}";
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_baseURL+"/api/user/login"),
Content = new StringContent(text, Encoding.UTF8, "application/json")
};
try
{
using (response = await client.SendAsync(request))
{
HttpResponseMessage _response = null;
//response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
//_response = response;
var body = await response.Content.ReadAsStringAsync();
var token = response.Headers.GetValues("auth-token").FirstOrDefault();
model.authToken = token;
model.name = body;
model.responseMessage = "Congratulations!";
return _response;
}
else
{
model.name = "";
model.responseMessage = await response.Content.ReadAsStringAsync();
return _response;
}
}
}
catch(Exception e) {
// model.responseMessage = e.Message;
return _response;
}
}
using "HttpResponseMessage _response = new HttpResponseMessage();" was setting the _response.StatusCode to be as "200" and the code was not dealing with that.

HttpClient.PostAsJsonAsync crushed without exception

I am trying to call an api(POST method) with HttpClient.PostAsJsonAsync. However, it stopped at httpClient.PostAsJsonAsync without any exception.
The source code as below:
public static async Task<oResult> PostApi(string JSON_sObject, string sEnd_Url) {
oResult oResult = new oResult();
var Data = JsonConvert.DeserializeObject(JSON_sObject);
var Url = "http://localhost:44340/" + sEnd_Url;
HttpClient httpClient = new HttpClient();
try {
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data); // it stopped here
if (response.IsSuccessStatusCode)
{
var sResponse_content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<oResult>(sResponse_content);
}
else
{
return oResult;
}
}
catch (Exception ex)
{
LogFile(ex);
return oResult;
}
}
Please advice me if any issue from the source code.
Thank you
you should not trying serialize deserialize twice
remove from your code
var Data = JsonConvert.DeserializeObject(JSON_sObject);
and replace
HttpResponseMessage response = await httpClient.PostAsJsonAsync(new Uri(Url), Data);
with this
var content = new StringContent(JSON_sObject, Encoding.UTF8, "application/json");
var response = await client.PostAsync(sEnd_Url, content);
also fix base httpclient address
var baseUri= #"http://localhost:44340";
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };
try {

why await does not wait untill httpclient postasync complets?

Im creating http client for consume some api.
Here is my client method calling to api endpoint.
public async Task<HttpResponseMessage> SendRequestAsync()
{
string adaptiveUri = "https://some-api/api/Authentication/AuthenticateThirdPartyUserAsync";
using (HttpClient httpClient = new HttpClient())
{
var json = JsonConvert.SerializeObject(new { userName = "uname", password = "123", applicantCode = "hello" });
var payload = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = null;
try
{
responseMessage = await httpClient.PostAsync(adaptiveUri, payload);
}
catch (Exception ex)
{
if (responseMessage == null)
{
responseMessage = new HttpResponseMessage();
}
responseMessage.StatusCode = HttpStatusCode.InternalServerError;
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
return responseMessage;
}
}
calling method is as follows
public async Task<IBaseStatus> Handle(InspectionAddedEvent domainEvent)
{
var tk = await _iAClient.SendRequestAsync();
return something;
}
but await does not wait untill postasync completes.
but when i use
httpClient.PostAsync(adaptiveUri, payload).GetAwaiter().GetResult()
it waits until post is complets.
can anyone have idea about this?
Thanks.
await _iAClient.SendRequestAsync(); definitely waits for the PostAsync.
I think the problem is that your are receiving an exception in SendRequestAsync and confuse the result.
Remove completely the try/carch block
public async Task<HttpResponseMessage> SendRequestAsync()
{
string adaptiveUri ="https://someapi/api/Authentication/AuthenticateThirdPartyUserAsync";
using (HttpClient httpClient = new HttpClient())
{
var json = JsonConvert.SerializeObject(new { userName = "uname", password = "123", applicantCode = "hello" });
var payload = new StringContent(json, Encoding.UTF8, "application/json");
return await httpClient.PostAsync(adaptiveUri, payload);
}
}
And try to catch it in the caller:
public async Task<IBaseStatus> Handle(InspectionAddedEvent domainEvent)
{
try
{
var tk = await _iAClient.SendRequestAsync();
return something;
}
catch(Exception ex)
{
//Probably return some IBaseStatus
}
}

asp.net core httpclient ArgumentNullException

I'm trying to make a POST request using HttpClient but it keeps throwing an ArgumentNullException.
on this call var response = await client.PostAsync(url, content);
I've set break points and verified that the values are populated.
Is there something I'm missing that would cause this?
public async Task<bool> PostSomeObject()
{
var transaction = new CreateTransactionRequest();
transaction.MerchantAuthentication.Name = "notmyName";
transaction.MerchantAuthentication.TransactionKey = "notMyKey";
transaction.TransactionRequest.TransactionType = "authOnlyTransaction";
transaction.TransactionRequest.Amount = 5;
transaction.TransactionRequest.Payment.CardCode = "999";
transaction.TransactionRequest.Payment.CardNumber = "5424000000000015";
transaction.TransactionRequest.Payment.ExpirationMonth = 12;
transaction.TransactionRequest.Payment.ExpirationYear = 20;
var url = "xml/v1/request.api";
using (HttpClient client = new HttpClient())
{
var sampleClassObjectJson = JsonConvert.SerializeObject(transaction);
client.BaseAddress = new Uri("http://localhost:56858/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(sampleClassObjectJson, Encoding.UTF8, "application/json");
//throws NullException on this call here
var response = await client.PostAsync(url, content);
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
throw new WebException("An error has occurred while calling PostSomeObject method: " + response.Content);
}
}
Based on a comment I've added a try catch for the ArgumentNullException
try {
var response = await client.PostAsync(url, content);
}
catch (System.ArgumentNullException ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
It's not stepping into the catch statement but in the Output from debug it throws the exception.
Here is the controller action that calls my Post method
public async Task<IActionResult> PaymentInformation(Payment paymentInfo)
{
var cookie = GetCheckoutCookie();
//if there isn't a cookie ID something went wrong, redirect to Index
if (cookie.ID == null)
{
return RedirectToAction("Index");
}
var cookieSession = CheckoutSession.getCheckoutSession(cookie.ID);
if (ModelState.IsValid)
{
var status = await PostSomeObject();
}
else
{
}
return PartialView();
}

System.Net.Http.HttpClient in [Universal Windows Platform] not working properly

I wrote simple method for getting data from (online) REST Service:
public async Task<Object> GetTask()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://111.111.111.111:8080/");
HttpResponseMessage result = await client.GetAsync("ABC/CDE/getsomeinfo");
if (result.IsSuccessStatusCode)
{
//Deserialize
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error" + ex);
}
return null;
}
Whenever i run this on UWP i'm getting catch exception:
The text associated with this error code could not be found.
A connection with the server could not be established
HResult 2147012867
Im trying to connect my client with restapi in internal network. In forms same code is working properly.
Try this
HttpResponseMessage response;
public async Task<string> webserviceResponse(string HttpMethod)
{
// check internet connection is available or not
if (NetworkInterface.GetIsNetworkAvailable() == true)
{
// CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
HttpClient client = new HttpClient();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
string GenrateUrl = "your url";
if (HttpMethod == "POST")
{
response = await client.PostAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "PUT")
{
response = await client.PutAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "GET")
{
response = await client.GetAsync(GenrateUrl);
}
var respon = await response.Content.ReadAsStringAsync();
string convert_response = respon.ToString();
return convert_response;
}
else
{
return "0";
}
}

Categories

Resources