The error handler in AngularJS is failing to run

Currently I am utilizing angularJS and spring 3.2.4 to handle REST exceptions in a particular way, shown below:

 @ExceptionHandler(MethodArgumentNotValidException.class)
     @ResponseStatus(value=HttpStatus.BAD_REQUEST)
     @ResponseBody
     public ErrorFormInfo handleMethodArgumentNotValid(HttpServletRequest req, MethodArgumentNotValidException ex, HttpServletResponse response) {

             String errorMessage = "gender string is out of range";
             String errorURL = req.getRequestURL().toString();
             System.out.println("Throwing exception from the exception handler");
             ErrorFormInfo errorInfo = new ErrorFormInfo(errorURL, errorMessage);
             return errorInfo;
     }

Whenever an argument validation failure occurs, it results in throwing a MethodArgumentNotValidException. However, I have noticed that while Spring 3.2 automatically converts objects into JSON format, I am unable to access the object in the error block of AngularJS without encountering an error stating "Response is undefined" as shown below:

completeRequest(callback=done(status, response, headersString), status=400, response="{"errorMessage":"http:/...string is out of range"}", headersString="Server: Apache-Coyote/1...MT\r\nConnection: close\r\n")angular-1.0.7.js (line 9333)
onreadystatechange()

I suspect that the issue lies in the object not being converted into JSON due to a peculiar header string.

Below is my JavaScript code snippet:

 $http.post('rest/create?cd=' + (new Date()).getTime(),
                            XYZ
                    .success(function(data) {
    alert('Data added successfully');                                               
                            }).error(function(data) {   
                                var errorInfo = data;
                                alert("data from server side"+errorInfo.errorMessage);
                        alert("Unable to process");
                    });

If anyone could offer assistance on this matter, it would be greatly appreciated. Thank you in advance.

Answer №1

Within the $httpProvider service of AngularJS, I implemented an interceptor that only runs for success and error scenarios. To handle cases where the response is 'undefined', I added the following code snippet within a promise:

 if(jsonStr.ERROR_URI != 'undefined')
      {
            var jsonStr = response.data;    
            console.log('inside error block');  
            console.log('response.status'+response.status); 
            console.log('response.data'+response.data); 
            console.log('response.data.ERROR_URI'+jsonStr.ERROR_URI);
            return $q.reject(response);
      }

This code simply rejects the response when it is undefined, effectively resolving the issue at hand.

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

Is there a way to concatenate arrays without using the Array.flat method?

I am encountering an issue with a specific function that I have const flat = function(arr, n) { if (n == 0) { return arr; } else if (n == 1) { let newarr = [] for (let i = 0; i < arr.length; i++) { if (Number.isInteger(arr[i])) ...

similar to a capture group but for a matched subdocument

In the database, there is a Chats collection with a participants subdocument structured as follows: { _id: '1', participants: [ { _id: 'A', seen: false }, { _id: 'B', seen: false } ], messages: [] } Each chat c ...

Creating an Angular ngFor directive with no data source. Let's construct the iterable to make it

When using *ngFor in Angular 2+, you can create an array of n elements to build the iterable (rows) like this: <table> <tr *ngFor="let row of rows"> </tr> </table> Is it possible to iterate over a number directly? Any suggest ...

Tips on boosting the speed and user-friendliness of your AJAX/REST application

Exploring the Essential Requirements of an Application I am currently developing a comprehensive application using AngularJS (but it could be any framework). This application interacts with a server built on Google App Engine through REST technology. Th ...

"Exploring the best method to utilize a for loop for updating an array of objects in

I'm looking to update a nested mongo document using a for loop with my node.js code below: //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierS ...

Is it possible to use the identical change function on numerous div elements?

How can functions be bound to multiple div elements effectively? $('#trigger1').change(function(){ // implement the code }); $('#trigger3').change(function(){ // execute the same code }); ...

When transferring a file path from a Xamarin Forms C# app to JavaScript, watch out for missing escape characters

I am facing an issue with my Xamarin Forms app where JavaScript is being called and a JSON string containing a path is sent as a parameter. The problem arises when the backslashes get double-escaped in C#, but only single backslashes remain when it reaches ...

Success function in Classic ASP with Ajax Form isn't functioning properly, but the complete function is working fine

When using Ajax and JS/Jquery, I am attempting to send a basic Contact form to a Classic ASP (aspemail) without reloading the page. <form id="form-submit" action="ASPEmail.asp" method="post"> Name<br> <input id="name" type="text"&g ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

Error found when combining a stopwatch with the react useState hook and setInterval, causing an additional interval to start when the stopwatch

I have implemented a stopwatch feature that includes start and pause buttons. The start button triggers setInterval while the pause button calls clearInterval. Initially, pressing start and then pause works correctly. However, if you press start again afte ...

help a figure leap within the confines of the artwork

Take a look at my jsfiddle here: http://jsfiddle.net/2tLCk/4/ When you press the up button, Mario jumps high into the air and then comes back down. However, if you press it again, he doesn't jump. How can I fix this issue so that when the up button i ...

Receiving a 404 error when attempting to use the 'import' statement within a script tag labeled as a module

I am currently working on a NodeJS project that utilizes Webpack for bundling and Express for serving. Whenever a user visits the root domain, they are served an index.html file containing a <script> block in the footer with a type of module. index. ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

Ways to avoid extra function loads in JavaScript

I'm currently working on an instant search feature and have some code implemented: $(function() { var timer; $("#searchterm").on('keypress',function() { timer && clearTimeout(timer); timer = setTimeout(doStuff, 800); tim ...

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

`Issues with integrating AngularJS controller and service`

Here's the code snippet for a tiny Angular application I'm working on: var myApp = angular.module("MyApp", []); myApp.factory("Items", function() { var items = {}; items.query = function() { return [ { ...

The error message shows: "Unable to retrieve property 'opts' from an undefined source in google-auth-library"

My current task involves retrieving tokens from Google for a specific user. Here is the code snippet I'm using: const util = require('util'); return util.promisify(oauth2Client.getToken, {context: oauth2Client})(googleToken).then(tokens ...

Is there a way to transform this Json array into a format that JQuery can interpret easily?

Having a bit of trouble with this issue. I'm not entirely sure how to get it working correctly. According to Firebug, the Json object (or possibly array) from my ajax request appears as follows: { "jsonResult": "[ {\"OrderInList\":1}, ...

Is there a way to use JQuery to open a new window on the same page when a link is clicked? It seems possible based

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Show Content with Lin ...

What is a Brief Illustration of the Jackson Scala Extension?

Is there a straightforward example available for utilizing Jackson serialization and deserialization with the Scala module for version 2.10? I am specifically interested in achieving JSON conversion using reflection without needing to annotate or assign fi ...