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

Guide to obtaining a file from c# using ajax

I am facing an issue while trying to send a file through ajax and unable to save it. I have attempted various serialization methods without success. Below, I have included the client-side and server-side code. Any assistance in determining whether I am fol ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

React component slider encountering issue of 'undefined property style reading'

I attempted to develop a component for a slider, but it seems to be malfunctioning. Upon the initial rendering, I encountered the error: 'cannot read property style of undefined...' When I logged x[slideIndex-1], initially it returns undefined ...

Adding HTML content using jQuery's document.ready feature

As a jQuery novice, I am attempting to incorporate a Facebook like button using the jQuery document.ready function. In my external Javascript file (loaded after the jQuery script), you will find the following code snippet: $(document).ready(function(){ ...

Tips for clearing a material-ui search input field with the help of a button

Currently, I am working on a tutorial that involves implementing react material-ui tables along with a search input textfield. I am attempting to enhance this by adding a button that not only resets the table report but also clears the search input textfie ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

Vue: Implement out-in transition where the incoming element appears before the outgoing element has completely disappeared

Check out my code on Codepen: here In this scenario, I have set up two div elements: Block 1 and Block 2. The functionality I am looking for is when a button is clicked, Block 1 smoothly translates to the left until it goes out of view. Once that happens ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...