Spring ResponseEntity & AJAX error function: cannot access the contents of the response body

SERVER: Spring Frames

I have a Spring controller that has a method that returns a ResponseEntity<String> .

For perfectly good queries, I return the following:

 return new ResponseEntity<>(OK_MESSAGE, new HttpHeaders(), HttpStatus.OK); 

But if there are any problems at runtime or catching the Exception, I return:

 return new ResponseEntity<>(ERROR_MESSAGE, new HttpHeaders(), HttpStatus.BAD_REQUEST); 

Where ERROR_MESSAGE contains a custom string for each selected exception type.

CLIENT PARTY: AJAX challenge

When this POST method is called and returns HttpStatus.OK, AJAX

 success: function (data, message, xhr) 

and I can easily access String OK_MESSAGE by accessing data .

Problem is that the POST method returns HttpStatus.BAD_REQUEST, AJAX

 error: function (xhr, status, errMsg) 
Called

but I cannot access String ERROR_MESSAGE sent by the server that I need to show to the user.

Any suggestions?

+5
source share
1 answer

On the controller, I return a ResponseEntity as follows:

 return new ResponseEntity<>("Enter the full url", new HttpHeaders(), HttpStatus.BAD_REQUEST); 

In JS, I would check the response line with the answer as follows:

 $.ajax({ url: 'http://localhost:8080/link', data: 'url=/www.stackoverflow.om', type: 'GET', contentType: 'application/json; charset=utf-8', success: function (data, textStatus, xhr) { alert(xhr.status); }, error: function (data, textStatus, xhr) { alert(data.responseText); } }) 
+4
source

Source: https://habr.com/ru/post/1210412/


All Articles