0

I want my servlet to return error code with data, so client can point out to the user what is wrong with the request. In case of exception when the data is invalid:

catch (UnvaildInputException UIE) {
            UnvaildCodes unvaildCode = UIE.getUnvaildCode(); //code 1 for example
            System.out.println(unvaildCode.getKey() + "-" + unvaildCode.getValue()); //prints error key-val
            System.out.println(unvaildCode.getValue());
            response.getWriter().print(HttpServletResponse.SC_BAD_REQUEST +":"+unvaildCode.getValue()); //trying to write a string as data
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST); //400
        }

Now on client side(angularjs) I am trying to access the data:

httpService.sendPost(vm.details, '/some/url').then(function (response){
        $log.log(response);
        $log.log(response.data);
});

The error:

TypeError: Cannot read property 'data' of undefined
    at formDirectiveJS.js:91
    at angular.min.js:126
    at m.$eval (angular.min.js:140)
    at m.$digest (angular.min.js:137)
    at m.$apply (angular.min.js:141)
    at g (angular.min.js:93)
    at t (angular.min.js:98)
    at XMLHttpRequest.u.onload (angular.min.js:99)
Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114

1 Answers1

1

You need to handle the error in an error handler, not the success handler.

From https://stackoverflow.com/a/35458437/1842905

$http.get(url)
.then(function (response) {
    console.log('get',response)
})
.catch(function (data) {
    // Handle error here
});
Michael A. Schaffrath
  • 1,992
  • 1
  • 14
  • 23