Spring ResponseEntity & AJAX error函数:无法访问响应体内容

时间:2022-09-25 23:59:40

SERVER SIDE: Spring Framework

服务器端:Spring框架

I have a Spring Controller that has a method that returns the type ResponseEntity<String>.

我有一个Spring控制器,它有一个返回类型ResponseEntity 的方法。

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.

ERROR_MESSAGE包含针对每种捕获的异常类型的自定义字符串。

CLIENT SIDE: AJAX call

客户端:AJAX调用

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

当调用POST方法并返回HttpStatus时。好的,AJAX

success: function (data, message, xhr)

is called and I can easilly access the String OK_MESSAGE by accessing data.

调用,我可以通过访问数据轻松访问字符串OK_MESSAGE。

The problem comes that POST method returns HttpStatus.BAD_REQUEST, AJAX

问题是POST方法返回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.

被调用,但是我不能访问服务器上的字符串ERROR_MESSAGEsent,我需要向用户显示。

Any suggestions?

有什么建议吗?

1 个解决方案

#1


4  

On the controller I return the ResponseEntity in the following way:

在控制器上,我以以下方式返回ResponseEntity:

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:

在JS中,我将按照以下方式检查响应错误字符串:

$.ajax({
            url: 'http://localhost:8080/link',
            data: 'url=/www.*.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);
            }
        })

#1


4  

On the controller I return the ResponseEntity in the following way:

在控制器上,我以以下方式返回ResponseEntity:

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:

在JS中,我将按照以下方式检查响应错误字符串:

$.ajax({
            url: 'http://localhost:8080/link',
            data: 'url=/www.*.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);
            }
        })