Spring ResponseEntity & AJAX error function:无法访问响应正文内容

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

本文关键字:访问 响应 正文 function ResponseEntity amp error AJAX Spring      更新时间:2023-09-26

服务器端:Spring Framework

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

对于完全好的请求,我返回以下内容:

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

但是如果在执行或异常捕获过程中有任何问题,我会返回:

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

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

客户端:AJAX 调用

当调用该 POST 方法并返回 HttpStatus.OK时,AJAX

success: function (data, message, xhr)

被调用,我可以通过访问data轻松访问字符串OK_MESSAGE

问题来了,POST 方法返回HttpStatus.BAD_REQUEST,AJAX

error: function (xhr, status, errMsg)

被调用,但我无法访问服务器发送的字符串ERROR_MESSAGE,我需要向用户显示该字符串。

有什么建议吗?

在控制器上,我按以下方式返回响应实体:

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

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

$.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);
            }
        })