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.