I have the following class that is used in a login form to check if the user is valid or not:
class LoginService
{
private const string URL = "http://localhost:3001/api/auth/";
private HttpClient client = new HttpClient();
public async Task<UserLoguedResponse> login(LoginRequest loginRequest)
{
string data = JsonConvert.SerializeObject(loginRequest);
HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage httpResponse = await client.PostAsync(URL, content);
//MessageBox.Show(httpResponse.StatusCode.ToString());
if (!httpResponse.IsSuccessStatusCode)
{
throw new Exception($"No se pudo establecer la conexion con la base de datos({httpResponse.StatusCode.ToString()})");
}
var response = await httpResponse.Content.ReadAsStringAsync(); // hasta aqui todo bien
UserLoguedResponse userLoguedResponses = JsonConvert.DeserializeObject<UserLoguedResponse>(response);// Newtonsoft.Json
return userLoguedResponses;
}
}
The problem that arises is that I want to generate an exception in case a badRequest is returned. But as far as I understand, beyond the fact that we generate the error, it will always execute the return of the function. Is there any way to avoid it? or somehow improve the behavior so that I can then catch the error and display it in a message?
I have very basic knowledge of Windows forms. In Javascript it would simply have returned the exception, but in C# it is very explicit to have to return a specific data type.
I'll help you with some details:
1. In order to better control what you return and have what you need at hand, you could start by creating a model that will serve you at any time as a Response, which contains the information of the data you want to return (result), the error that could occur (message) and an error code to validate (codError). Something like:
2. Now with this model, you can put it as a return of any method that you need it. For example in your case it would no longer return
Task<UserLoguedResponse>
, but you would return aTask<Response>
. Something like this:3. I suggest making use of the block
try catch
to do good error handling.4. To handle the error and validate that everything is correct with the method you can validate as follows, or you could also validate with the error code with the same logic as the following code:
I hope this helps you.