Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring ResponseEntity & AJAX error function: can't access response body content

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_MESSAGEsent by the Server, which I need to show the user.

Any suggestions?

like image 739
charliebrownie Avatar asked Jan 05 '15 17:01

charliebrownie


1 Answers

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);
            }
        })
like image 172
liorsolomon Avatar answered Jan 02 '23 07:01

liorsolomon