SERVER SIDE: Spring Framework
I have a Spring Controller that has a method that returns the type ResponseEntity<String>
.
For completely good requests I return the following:
return new ResponseEntity<>(OK_MESSAGE, new HttpHeaders(), HttpStatus.OK);
But if there's any problem during the execution or Exception catching, I return:
return new ResponseEntity<>(ERROR_MESSAGE, new HttpHeaders(), HttpStatus.BAD_REQUEST);
Where ERROR_MESSAGE
contains a customized String for each type of Exception catched.
CLIENT SIDE: AJAX call
When that POST method is called and returns HttpStatus.OK, AJAX
success: function (data, message, xhr)
is called and I can easilly access the String OK_MESSAGE
by accessing data
.
The problem comes that POST method returns HttpStatus.BAD_REQUEST, AJAX
error: function (xhr, status, errMsg)
is called but I cannot access the String ERROR_MESSAGE
sent by the Server, which I need to show the user.
Any suggestions?
On the controller I return the ResponseEntity in the following way:
return new ResponseEntity<>("Enter the full url", new HttpHeaders(), HttpStatus.BAD_REQUEST);
In the JS I would check the response error string in the following way:
$.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);
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With