0

I have an ASP.NET Core Web API to which I send requests from my ASP.NET Core Web Application. I have implemented Global error handling in my Web API, and I am returning customized error messages. I have tested this on POSTMAN and it seems to work well. My problem is, when I do a request from my web application and the API returns an error, I cannot see/access my custom error message. For example, if I am trying to insert a record and the record already exists, I am returning a 409 error code and a message explaining to the user that the record exists. This is in JSON, Like below...

{
    "StatusCode": 409,
    "Message": "The donor - AGRA - already exists. Please provide a unique donor Id"
}

The status code is for my own consumption in the web application. I would like to display the error message (to the user) in the web app.

Further to that, I am using AJAX to post my request to the API, and check for responses.

function addDonor(obj, url, text) {
    swal({
        title: 'Do you want to proceed?',
        text: text,
        type: 'warning',
        buttons: true,
        dangerMode: true,
    })
    .then(function (isConfirm) {
        if (isConfirm) {
            $.ajax({
                type: 'post',
                url: url,
                data: obj,
                dataType: 'json',
                async: true,
                success: function (res, statusText, xhr) {
                    if (res) {
                        getDonors();
                        $('#adddonormodal').modal('hide');
                        swal({
                            title: "Success!",
                            text: res.message,
                            icon: "success",
                        });
                     } else {
                        swal({
                            title: "Error!",
                            text: res.message,
                            icon: "error",
                        });
                    }
                }
            });
        }
    });

}

I have tried to implement Try..Catch in my web app, but I only get the status code 409 without the custom message. Same goes for Global Error handling in the web app.

To be exact, this is how I am sending the request to the API

public static string PostToApi(string url, string Postdata, string header)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                var data = Encoding.ASCII.GetBytes(Postdata);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = data.Length;
                request.Headers.Add("Authorization", header);
                using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); }

                var response = new StreamReader(((HttpWebResponse)request.GetResponse()).GetResponseStream()).ReadToEnd();

                return response;
            }
            catch (Exception ex)
            {
                string err = CleanRes(ex.Message);
                return err;
            }

        }

I need to get the JSON error message in ex.Message. Like I explained above, I am only getting the Status Code with the generic error message... "The remote server returned an error: (409) Conflict."

I am at my wits end on how to read the exact error message on my web app and display it to the user. Please help.

Onsongo Moseti
  • 439
  • 5
  • 10
  • You can try using `$ajax().done();` it is better than the success implementation. look here https://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done – Bosco Jun 15 '19 at 21:18
  • Bosco, I have added more detail to my question. Hopefully, the question is clearer now. I need to get the exact same JSON error message I am sending from the API to the client. – Onsongo Moseti Jun 15 '19 at 21:44
  • 1
    Does the `CleanRes` method return `Json`? if yes use `return Content("your string");` – Bosco Jun 15 '19 at 21:49
  • I solved the problem by using HttpClient to call my API. HttpClient does not throw any error when the HTTP response contains an error code, but it sets the IsSuccessStatusCode property to false. In my controller I use the following code to serialize the HTTP content to a string as an asynchronous operation var responseBody = await response.Content.ReadAsStringAsync(); After that I can convert my JSON string to an object and access the error/success message and the Status Code too. – Onsongo Moseti Jun 19 '19 at 00:59

0 Answers0