Reading 409 response json in production cannot read custom error message from server

Viewed 45

I have an asp.net core MVC server set up, I am trying to enable some better error handling. However when I deploy my changes to production environment I have a discrepancy in my server responses when dealing with 4xx errors.

When running on my local host i am able to send custom response data back to the client and read this data no problem, however when i attempt the same thing after live deployment I cannot read the responses the same way And I do not understand why.

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!")
}

So it seems the custom error message i send when sending the 409 response is not there in the client in production, however, the success message is i can read it as expected and display the message, however when trying to read the response.json() after checking if response is ok (and when it is not) the response message is "SyntaxError: Unexpected token T in JSON at position 0" which based on some other research suggest it is undefined.

So my main questions are,
1- where is my error message for failures?
2- Is there a way i can get it display the error message, or can i only send http response code for error?
3- why does it work for success response but not error?
4- why is there this difference btwn localhost vs production is this a server configuration issue?

Thanks

1 Answers

After Much investigation, it turns out the source of the issue was in the web.configurations.

Since the project is being inside of another web app i had to add a section to my web.config which specifies a different custom error handling method than the rest of the site. specifically i added the below

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

And Now i am able to parse the Error response custom text in my JS and display the message from the server

Related