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

How can AngularJS utilize variables from an external JavaScript <script> file within an HTML document?

As someone unfamiliar with AngularJS, I have a simple inquiry regarding the subject. The code on my page begins by defining an app and controller: <script> var isisApp = angular.module('isisApp', []); isisApp.controller('Acco ...

The unexpected blank space appearing beneath my website as a result of images and videos placed on the

There seems to be some random white space on my website between the main body elements and the footer. Interestingly, removing the cat image and videoplayer eliminates this white space. However, I don't want to remove them completely, so I'm tryi ...

JavaScript attaching a function to an element within an array

Can anyone explain why I am unable to assign the toUpperCase method to a specific value in an array like shown below? I'm a bit confused because I thought objects were mutable and manipulated by reference. Maybe my understanding is incorrect? var ary ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Error message displayed in Ajax jQuery shows '[object Object]'

There seems to be an issue with this code on certain computers. I have a basic AJAX call set up to display a list of batches in a select tag. function show_batch(class_id,batch_id){ if(class_id){ $.ajax({ url:root_path+"module/fee_ ...

Retrieving output from a JavaScript function

When running the code, the following logs are generated: "generating my graph" myMain.js:110 "Getting credits" myMain.js:149 "debits array is 3.9,4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8" myMain.js:169 "Credits data = 10.7,20.5" myMain.js:156 ...

The self-made <Tab/> element is not functioning properly with the ".Mui-selected" class

I have customized a <Tab/> element and I want to change its selected color using Sandbox demo code export const Tab = styled(MuiTab)({ "&.Mui-selected": { color: "red" } }); However, I've noticed that: 1. Apply ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

Utilizing a different file to arrange and establish state

In a separate file called Origin.js, I have some data (objects) stored. This data is exported using the spread operator within an object named OriginState: Origin.js //info const info = { title: '', year: '', }; //images const ...

GSON threw an error: was expecting BEGIN_ARRAY but encountered BEGIN_OBJECT instead

Hello, I have a specific question regarding parsing a JSON file with GSON. The JSON structure is as follows: { "BUYER": { "IGN": "MGlolenstine", "ProductID": "51" }, "BUYER": { "IGN": ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

Encountering a problem with parsing a JSON object using the .map

After receiving this JSON response, my main goal is to extract the value located in the identifier. By utilizing console.log, I am able to analyze the structure of the object: Object {rows: Array[33], time: 0.015, fields: Object, total_rows: 33} fields: O ...

Angular 2 - Karma is having trouble locating the external template or style file

The file structure for this project (taken from the Angular 2 official site) is as follows: https://i.stack.imgur.com/A6u58.png Upon starting Karma, I encountered errors indicating that two files were not found under /@angular/... To resolve this issue, ...

Why is my JavaScript method not working and throwing an error?

Attempting to streamline my code by creating a separate method for calling an ajax function in multiple places. When I try to use the separate method instead of calling it directly, it doesn't work as expected. data: columns[5], type: 'a ...

What could be causing the directive to not trigger the controller method of mine?

Having trouble with my directive not calling the controller method. Here's the code I'm using: Controller: exports.controller = ['$scope', function($scope) { $scope.addParamter = function () { console.log("here ...

The React-Toastify module is missing

Having issues with react toast plugin displaying an error. Prior to attempting to use the toast feature, I executed this command: npm install --save react-toastify The following error is being shown in Google Chrome Console: ERROR in ./src/Pages/Login ...

What is the best way to show the associated ul tag?

I've constructed the following HTML: <input id="<code generated id>" type="text" value="select"/> <div id="<code generated id>" class="popup"> <ul id="<code generated id>" class="none"> <li>A</li& ...

Show HTML form elements on the page using jQuery or JavaScript

Is there a jQuery or JS library that can perform the following task: If the user inputs 'x' in A01, then make A01_1 visible. Otherwise, do nothing. <form id="survey"> <fieldset> <label for="A01">A01</label&g ...

JavaScript: End the program upon clicking CANCEL

Scenario: In my application, there is a confirmation pop-up message that appears when I try to save an entry. Clicking the OK button proceeds with saving the entry, while clicking the CANCEL button should go back to the booking content page - this functio ...

Removing a JSON file using PHP

Currently, I am in the process of writing a json-file within a newly generated folder. My goal is to automatically delete this folder along with its contents after an hour has passed. Here's what I have attempted: $dir = "../tmpDir"; $cdir = scan ...