AngularJS http requests are not redirecting to the errorCallback

Currently, I am utilizing angularjs to make calls to my Rest web services, but I am encountering an issue with error handling. Below is an example of one of my http calls:

$http({
    method: 'POST',
    url: "tr"+licenseSelected, //angular need string in url
    headers: {'Content-Type': 'application/json'},
    data : updatedLicense,
    beforeSend: function() {
        waitingModal.showPleaseWait();
    },
    complete: function() {
        setTimeout(function(){
            waitingModal.hidePleaseWait();
        }, 1000);
    }
}).then(function successCallback(response) {
    if (response.data.success==true){   
        licenseTable.ajax.reload();
        $('#updateLicenseModal').modal("hide");
        notifyMessage(response.data.result, 'success');
    } else {
        notifyMessage(response.data.result, 'error');
    }                       
}, function errorCallback(response) {
    window.location.href = "/ATS/500";
});

I am aiming to display a 500 page in case an error occurs during the http request (such as server downtime or incorrect URL), but it seems that the errorCallback is never triggered. Could there be an error in my code? Where could the fault lie? Thank you. Here is an example of a response that I am unable to handle in the error code:

{
"status":422,
"exception":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message":"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\"",
"stacktrace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"tr71\",
...
}

Example of a web service:

@Override
    @RequestMapping(value = { "/license"}, method = RequestMethod.POST)
    public @ResponseBody Response createLicense(@RequestBody ClientLicenseForm clientLicenseForm) {
        try{
            administrationService.createLicense(clientLicenseForm);
            return new Response(true, true, "Your license has been created!", null);
        }catch(Exception e){
            ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
            LOG.error("Threw exception in AdministrationControllerImpl::createLicense :" + errorResponse.getStacktrace());
            return new Response(false,false,"Error! Your license hasn't been created!",errorResponse);
        }
    }

This could potentially be the issue (wrapping JSON response inside another object), but how can I rectify it? https://i.sstatic.net/3h9wL.jpg

UPDATE I have adjusted the code as follows, and will perform a test:

}).then(function successCallback(response) {
            if (typeof response.data.success == 'undefined'){
                window.location.href = "/ATS/500";
            }else if (response.data.success==true){ 
                licenseTable.ajax.reload();
                $('#updateLicenseModal').modal("hide");
                notifyMessage(response.data.result, 'success');
            } else if(response.data.success==false) {
                notifyMessage(response.data.result, 'error');   
            }
        }, function errorCallback(response) {
            window.location.href = "/ATS/500";
        });

Answer №1

When it comes to your comments, a json response is received (most likely with a 200 header). The error callback will not be triggered if the header response shows a 200 status code.

There are two ways to handle this:

  1. Adjust the backend to return the correct status header code.

  2. Verify if the response is valid in the successCallback

    if (response.data.exception) {
        window.location.href = "/ATS/500";
    }
    

NOTE: It is not ideal for the server to return this type of error along with a stack trace.

Examples of Exception Handling

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

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

Struggling to find the right look for identical items

I'm currently working on a project where I need to identify and hide duplicate values in a table. The goal is to only display unique values in the first column and hide any duplicates from view. However, I'm running into an issue when trying to h ...

Is there a way to automatically recalculate the "Total Price" when the input values are adjusted?

Whenever I add an item to the cart, it gets appended to the row in the shopping cart, and the price adjusts accordingly. However, I'm having trouble getting the price to adjust whenever I change the input values (input type: "number"). I can't se ...

Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet: <p:inputText value="#{customerLController.surn ...

Why isn't the max width applying to an input element wrapped within a Div?

Hey there! I recently created a Search Bar and wrapped it inside a div with a max-width of 500px, but for some reason, the max-width is not working as expected. I searched on Stack Overflow and came across a helpful link on Why would max-width not work on ...

Solving a $http GET request within a multi-view router setup with ui.router

I am currently faced with a challenge of resolving http ajax get calls with multi-views using the UI-Router library for AngularJs. JS (app.js): angular .module("goHenry", ["ui.router"]) .controller("MainCTRL", MainCTRL) .config(configB); f ...

Any ideas on how to fix the error that pops up during the installation of the bootstrap package in Node

The npm command is not recognized as a valid cmdlet, function, script file, or operable program. Please double check the spelling of the command and ensure that the path is correct before trying again. This error occurred at line 1. npm i bootstrap + ...

Tips for designing scrollable overlay content:

I am currently in the process of building a page inspired by the design of Hello Monday. Right now, I have added static content before implementing the parallax effect and auto-scroll. Here is my progress so far: Check out the Sandbox Link One challenge ...

Retrieve an Excel file using Selenium through a URL, but only obtain JavaScript code instead

I am attempting to download an Excel file using its URL, but all I receive is JavaScript code. I'm unsure of how to retrieve the actual file instead of just the JS code. Here is my current code: # -*- coding: utf-8 -*- from selenium import webdrive ...

Simple steps for integrating JavaScript ads into your WordPress website

Received an advertisement from my client, a 300x250 ad in ad folder consisting of 1 HTML file, 1 JavaScript file, and 1 images folder. Questioning how to integrate these files into the side panel of my Wordpress website's homepage. I've spent a ...

Question: How come I am receiving the error message "TypeError: Cannot read property 'toLowerCase' of undefined" in React JS?

Hi there, I'm new to this and trying to create a search filter. However, I keep encountering an error that says: Error: Cannot read property 'toLowerCase' of undefined It seems like the issue is related to the data type used with toLowerCa ...

Executing PHP code inside Angular may require configuring a backend server

Currently, I am implementing angular to add page transitions on a wordpress website. The way it works is that my site initially loads a standard wordpress page, runs its PHP code, and then fills the body with angular components. These angular elements are ...

Struggling to make the JavaScript addition operator function properly

I have a button that I want to increase the data attribute by 5 every time it is clicked. However, I am struggling to achieve this and have tried multiple approaches without success. var i = 5; $(this).attr('data-count', ++i); Unfortunately, th ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

Whenever I enter a narrative into my text box, it must interact with this API

Whenever I enter a story in the text box, it should trigger this API call: The retrieved data should be displayed in the browser. Currently, the API call is not being made. All the relevant code can be found in 'searchbar.js'. Could you please ...

Ways to troubleshoot problems with lifecycle scripts

Let me walk you through the steps that led to this error: I created a new folder for my project I opened the terminal within the folder and ran the command npm init I added an index.js file to the folder I ran the command npm install Finally, I executed t ...

Adjusting the height of a textarea with javascript

I am trying to reset the contents and height of an auto resizing textarea element. My attempts so far include: document.getElementById('textarea').value = ''; As well as: document.getElementById('textarea').attribute(&apos ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...