What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object.

If the login details are accurate, the backend will respond with a JSON object containing a validation key for successful verification. (such as: [{"result":"VALID"}] )

In the case of incorrect login credentials, only a 500 error is provided.

The issue arises when encountering the 500 error; instead of taking action because the result is not "VALID," the script simply stops due to the lack of an object to validate.

How can I identify from the front end that a 500 error has been received and then trigger the function "bootThem()"?

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null); 
}

window.onload = function () {
    // obtain the URL from storage.
    var fullURL = localStorage.getItem("fullURLStored")

    // if the URL is empty, redirect back to the login page.
    if(fullURL == ""){
        bootThem(); 
       }
       
    // send the URL to the server.
    readTextFile(fullURL, function (text) {
        
        var data = JSON.parse(text);

        if(data[0].result !== "VALID"){
            bootThem(); 
        } else{
            //perform actions
        }
    }); 
} 

Answer №1

Take a look at the following example where I have created a mock API response simulating a 500 error and handling it:

  if (rawFile.readyState === 4 && ((rawFile.status === 200) || (rawFile.status === 500))) {
      console.log("fired");
      callback(rawFile.responseText);
    }

https://jsfiddle.net/asutosh/vdegkyx2/8/

Answer №2

With a nudge from Asutosh, I managed to tweak my function to handle situations where a 500 error is detected in the JSON call. This adjustment allows the user to be booted out if an error occurs or pass through smoothly when there are no issues.

The solution proved handy for tackling those pesky 500 errors that cropped up in the JSON response:

function bootThem() {
   //execute code to reset session and return user to login page.
}

function readTextFile(file, callback) {
  var rawFile = new XMLHttpRequest();
  rawFile.overrideMimeType("application/json");
  rawFile.addEventListener('error', () => {
    console.log("error code");
  });

  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function() { 
    if (rawFile.readyState === 4 && (rawFile.status === 500)) {
        console.log("500");
        bootThem(); 
        callback(rawFile.responseText);
    } 
    if (rawFile.readyState === 4 && (rawFile.status === 200)) {
        console.log("200");
        callback(rawFile.responseText);
    }

  }
  rawFile.send(null);
}


window.onload = function () {
    // get the url from storage.
    var fullURL = localStorage.getItem("fullURLStored")

    // if the URL is empty, boot them back to the login page.
    if(fullURL == " "){
        bootThem(); 
       }
       
    // send the URL to the server.
    readTextFile(fullURL, function (text) {
        
        var data = JSON.parse(text);

        if(data[0].result !== "VALID"){
            bootThem(); 
        } else{
            //do stuff
        }
    }); 
} 

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

Adding options to a dropdown menu using jQuery and Ajax technique

After retrieving data from an Ajax call and attempting to append option values to a dropdown generated in jQuery, it doesn't seem to be working as expected. Here is the code snippet: $(document).on('focusout', '.generate', functio ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

Tips for using an array as a jQuery selector in JavaScript

Managing an element with an array id id="x[]" can be tricky when it comes to dynamically changing content based on database entries. This specific element is essentially a delete button for removing table rows from the database. <div align="center" id= ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Creating a shimmering glow for a dynamic AJAX div block in real-time

I created an Ajax code that retrieves results from a txt file in real time, which are then automatically displayed in a div block using the following lines: if (xmlhttp.responseText != "") { InnerHTMLText = xmlhttp.responseText + document.getElementBy ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Encountering a Typings Install Error When Setting Up angular2-localstorage in WebStorm

I am currently using Windows and WebStorm as my development environment. I attempted to install the angular2-localstorage package by running the command npm install angular2-localstorage, but encountered an error. After realizing that the angular2-localst ...

Solving Issues with URL Parameters and AJAX

My JSP page has a JavaScript function called loadData() that is triggered when the page loads. This function makes an AJAX request to a servlet in order to retrieve data and return the necessary HTML content to display on the page. I am trying to call thi ...

Tips for transforming JSON output from Facebook's graph API into a different format

Feeling a bit lost on whether I'm on the right track, I came across a snippet of code in a tutorial video on YouTube. Unfortunately, the series was left incomplete with just the content from the initial video. I've been attempting to access all ...

Minimize/Maximize Swagger Response Model Class View

After successfully integrating Swagger API documentation with my rest services, I encountered a challenge. The Swagger page appears too lengthy due to the numerous response classes in my project, requiring users to scroll extensively to find information. ...

Discovering applied styles based on component props in Material-UI v5 using browser developer tools

When working with Material UI v4, I found it easy to identify which styles are applied by component props classname using browser dev tools. This allowed me to override specific styles of the component effortlessly. However, in Material UI v5, I am unsure ...

When working with a barcode font in Chrome, using style.fontFamily may not be effective, but utilizing className can achieve the desired result

Take a look at this HTML snippet: <style> .barcode { font-family: 'BC C39 3 to 1 Medium'; } </style> <div><span id='spn'>1234567</span></div> This code will apply a barcode font style: <script> ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...

Is it necessary to download and install plotly if I am using the cdn in my HTML file?

I'm currently developing an online application using Flask. The user input is collected with d3.js and sent to app.py, where it is used for an API call to retrieve the necessary data. This data is then returned in JSON format to JavaScript for renderi ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

Traversing Through a Complicated JSON Structure

An application I developed can accept faxes in XML format and convert them into JSON objects to extract the necessary information, specifically the base64 string within the "file contents" variable of the document. Here is the code snippet: exports.recei ...