2

I am developing (at least attempting anyways...) a xamarin android app with connection to API. Below is a basic example of what I am trying to do with a Post. I am not sure how to return the error message (not just code) back to client? I am open to a better way of doing this as long as a complete example can be provided.

API code:

[HttpPost("Consume")]//*
public IActionResult ConsumeInventory([FromBody] Part part)
{
    try
    {
        _repo.ConsumeInventory(part);
    }
    catch (Exception ex)
    {
        //ModelState.AddModelError("Error", ex.Message);
        return NotFound("Not Enough Inventory");
    }

    return Ok(part);
}

Client side call:

public async Task<HttpResponseMessage> UpdatePartAsync(Part part, string post_url)
{
    string jsonString = JsonConvert.SerializeObject(part);
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsync("invcount/" + post_url, new StringContent(jsonString, Encoding.UTF8, "application/json"));

    if (response.StatusCode == HttpStatusCode.NotFound)
    {...//Would like to display "Not enough Inventory" in here}

    return response;        
}

2 Answers 2

4

Even when the API call is unsuccessful, you can read the content of the response by using HttpResponseMessage.Content.ReadAsStringAsync()

if (response.StatusCode == HttpStatusCode.NotFound)
{
    // Would like to display "Not enough Inventory" in here}
    var resposeContent = response.Content?.ReadAsStringAsync();
    var result = JsonConvert.DeserializeObject<ServerResponse>(resposeContent);

    // this guy will have your human-readable description or in your case, you can display the whole `result` string
    Debug.WriteLine(result.Description); 
}

And define you ServerResponse class as you designed your API. I regularly inherit all my API responses from the same base class so on the client side I can parse them first to check for custom directives from server (custom codes which are not always errors) message:

public class ServerResponse
{
     public string Code {get;set;}
     public string Description {get;set;}
}

ps: beware, HttpResponseMessage.Content could be null in certain cases.

Sign up to request clarification or add additional context in comments.

Comments

3

Your question has nothing to do with Xamarin. In this case Xamarin app is just a front-end that consumes your API.

Generally speaking, you should generalise your error responses and if needed log the exception to DB for a further analysis. JSON example:

{
  "Code": 1000,
  "Description": "Human readable description",
  "Id": "6a154fd3-4142-4a9c-80b5-c635e84123fa"
}

Code for internal error code in the system and Id for identifying the stack trace in the DB. So your end-user will get a nice human readable description and an Id that he could use to contact the support.

Technically, use a ExceptionFilterAttribute in order to catch and return a generalised error response to your clients. Reading Global Error Handling in ASP.NET Web API 2 may also give you a better overview.

In your client app after you get a response from the API you can check if the response has a success status code:

if (!response.IsSuccessStatusCode)
{
    // Deserialize error message
}

P.S.: Stackoverflow is not a coding service, so there will be no a complete example. Hope you will get some ideas from my answer on how to handle it in a better way.

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.