Error messages cannot be custom in production when reading a 409 response JSON from the server

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

Answer №1

After conducting a thorough investigation, I discovered that the root cause of the issue resided in the web configurations.

Since the project is nested within another web application, I had to include a section in my web.config that specifies a unique custom error handling method different from the rest of the website. Specifically, I added the following:

<location path="webdb">
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
            <clear/>
        </httpErrors>
    </system.webServer>
</location>

As a result, I am now able to interpret the customized error response in my JavaScript and display the server's message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Infuse the theme into the sx prop of MUI 5

The code snippet above was originally written using MUI v4: const useStyles = makeStyles(theme => ({ toolbarMargin: { ...theme.mixins.toolbar } })) To update this code to MUI v5 and utilize the sx prop, I attempted the following implementation: ...

Implementing a dual hover effect on a Div element

I am working with HTML code that includes an image and text <div class="subcontainer1"> <img src="a.png" alt="" class="imgcolumn"> <h3 class="header3">Hello</h3> </div> This setup places the content above the image. ...

What is preventing me from navigating to other pages in my React application?

Recently, I have been experimenting with ReactJS and encountered an issue where I couldn't access my other pages. The code snippet provided below seems to be the root of the problem. I am in the process of developing a multi-page application using Re ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

Azure ASP.NET REST Web Service Call not being processed

After working with the new Azure Machine Learning Service, I successfully created a web service from my model. When I use a HTTPS tool to POST to the service, I receive the expected results. The issue arises when trying to integrate my ASP.NET code with t ...

Choosing a token utilizing JSON.NET and LINQ

I am working with XML data in C# and have the following structure: string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<!--PowerStats Table Model Paramter Template Ver 1.0 Created on 11/19/2013-->" + ...

What is the best way to store user input in local storage using Vue.js?

Following the official Vue.js site, I have been trying to implement Framework 7. However, when using an input field, [object InputEvent] is displayed both when typing text and attempting to save it. Is there a way to store a name in local storage and have ...

Executing a function after a subscriber has finished in Angular 8+

Welcome fellow learners! Currently, I am diving into the world of Angular and Firebase. I am facing an interesting challenge where I fetch ticket data from my collection and need to add new properties to it. However, the issue arises when my ordering funct ...

Can I use the mouseover event on an image to display a sibling div?

Hi everyone! I'm fairly new to web development and I could really use some advice. I'm trying to implement a mouseenter event on an img tag to show a sibling div, but I'm encountering some strange behavior. The mouseenter event seems to be w ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

Learn the process of dividing an image into segments and combining them back together in C#

I am looking to divide an image into separate parts, rearrange them in a different order, and then reassemble the images. How can I achieve this using C#? ...

What is causing a single state update when setState is called twice in React?

It seems like I'm making a beginner mistake in React as I am trying to call the "addMessage" function twice within the "add2Messages" function, but it only registers once. I believe this issue might be related to how hooks work in React. How can I mod ...

The system is facing difficulty in accessing the property 'user_first_name' as it is currently undefined

I'm having trouble registering a user with expressjs/mongoose as I keep receiving the error: TypeError: Cannot read property 'user_first_name' of undefined at C:\Quiz webPolitica\server.js:20:24 at Layer.handle [as handle_request] ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

Unable to bring JavaScript into an HTML document

I am diving into the fundamentals of JS and HTML, starting with a simple script. Here is my test.js file: document.getElementById("test").innerHTML = "Loaded js file"; And here is my test.html: <!DOCTYPE HTML> <html lang="de"> <head> & ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

unable to make changes to user in asp.net

Within my Account.aspx file, the following code is present: <table> <tr> <td> <asp:Label ID="user_lbl" runat="server" Text="Username:"></asp:Label> </td&g ...

Stylish Wave Animation Effects in CSS for iPad Native Application

The ripple effect on the iPad Native app is malfunctioning. The effect is mistakenly applied to all buttons in the navigation instead of just the li elements. Please identify the error and provide a solution. (function (window, $) { $(function() ...

What are the disadvantages of using getBoundingClientRect() in ReactJS?

I recently incorporated the getBoundingClientRect() method into my project. However, a fellow React developer expressed concerns about its browser compatibility. In theory, shouldn't Webpack or Babel handle such compatibility issues? ...