After setting up my asp.net core MVC server, I decided to implement better error handling. However, upon deploying the changes to the production environment, I noticed a discrepancy in how my server responds to 4xx errors.
While everything works fine on my local host and I am able to send custom response data back to the client with no issues, the same cannot be said for live deployment. I find myself unable to read the responses in the same way, leaving me puzzled about what could be causing this difference.
Controller
[HttpPost]
public JsonResult SaveRecord([FromBody]NewsLanguage newLanguage)
{
//NewsLanguage newLanguage = new NewsLanguage()
try
{
_context.NewsLanguages.Add(newLanguage);
_context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Response.StatusCode = 409;
string errMsg = ex.Message;
if (ex.InnerException != null)
errMsg = ex.InnerException.Message;
return Json(new { status = "Error", message = errMsg });
}
Response.StatusCode = 200;
return Json(new { status = "success",
message = "New News Language Saved Successfully!" });
}
fetch request
try {
const response = await submitForm("/saverecord", newsLanguage, "POST");
console.log(response);
if (response.ok)
handleResponse(response, newsLanguage);
else {
const err = await response.json();
throw new Error(err.message || err.statusText)
}
} catch (err) {
console.log(err);
handleErrorResponse(err, newsLanguage);
}
function submitForm(route, newsLanguage, method) {
const requestOptions =
{
method: method,
headers:
{
'Content-Type': 'application/json'
},
body: JSON.stringify(newsLanguage)
};
return fetch(parurl + route, requestOptions);
}
async function handleResponse(response, newsLanguage, method) {
const data = await response.json();
console.log(response, data)
if (data.status === "success") {
//have to close modal this way since using
//jquery hide leave backdrop open and causes
//issue with subsequent modal openings
document.getElementById("ModalFormClose").click();
toastr.success(data.message, "PERLEWEB DATABASE INTERFACE");
if (method !== "DELETE") {
let table = $('#example').DataTable();
table.row.add({ "id": newsLanguage.Id,
"languageName": newsLanguage.LanguageName }).draw();
} else {
var table = $('#example').DataTable();
table.row($(this).parents('tr')).remove().draw();
}
} else {
toastr.error(response.responseJSON.message, "ERROR!")
}
}
function handleErrorResponse(errorMsg) {
toastr.error(errorMsg, "ERROR!")
}
It appears that while the success message is being displayed as expected, the custom error message sent during the 409 response is not reaching the client in the production environment. Additionally, when trying to read the response.json() after confirming that the response is not okay, an error message stating "SyntaxError: Unexpected token T in JSON at position 0" arises, hinting at an undefined issue based on various research.
These observations raise some key questions:
1- Where is the error message for failures?
2- Is there a way to display the error message, or must only the HTTP response code be sent for errors?
3- Why does it work for successful responses but not for error responses?
4- Could the difference between localhost and production environments be attributed to a server configuration problem?
Thanks