How to get a return from a Webapi Exception?

Asked

Viewed 87 times

1

I have the following method that makes a request for Delete to my WebApi:

[HttpPost]
public async Task<IActionResult> Delete(int id, IFormCollection frmCollection)
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("http://localhost:6000/api/");
    var resposta = await httpClient.DeleteAsync($"cencus/{id}");

    //... TRATAR A EXCEPTION AQUI
}

The return method of my API is as follows:

[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
  DatabaseConnector dbConn = new DatabaseConnector();
  try
  {        
    int affected = dbConn.Connection
        .Execute($"DELETE FROM CENCUS WHERE CODCEN = {id}");

    if (affected > 0)
    {
      return NoContent(); //203
    }
    else
    {
      return NotFound(); //404
    }        
  }
  catch (Exception exp)
  {
    return Conflict(exp); //409
  }
  finally
  {
    dbConn.Dispose();
  }
}

My question is: in case exception when executing the command SQL, how I will access the information as a message from Exception in response?

  • Return the error status and add the message you want...

  • 1

    you here already send the problem to your Webapi (return Conflict(exp); //409) although I don’t know if that’s good ... !

  • What is your question, specifically? I can’t understand what you intend to do...

2 answers

0


In fact it is simpler than I imagined, just try to convert the return and see if the conversion was a success:

if (!resposta.IsSuccessStatusCode)
{
    Exception ex = await resposta.Content.ReadAsAsync<Exception>() as Exception;

    if (ex != null) {
        //O retorno da API foi uma exception...
    }
}

-1

If I understand your doubt:

try
{
  executa código
}
catch(WebException wexp)
{
  ...wexp.response...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.