有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从Spring响应中检索描述性消息。发送错误(…)在用户端?

我在Spring控制器中定义了一个异常处理程序,如下所示:

@ExceptionHandler(Customized4ExceptionHandler.class)
public void handleCustomized4Exception(
    Customized4ExceptionHandler ex,
    HttpServletRequest request,
    HttpServletResponse response) throws IOException {

        response.sendError(HttpStatus.EXPECTATION_FAILED.value(),
        "zzzzzzz");

}

触发错误时,我在用户端得到以下信息:

enter image description here

错误代码正确,但不显示“zzzzz”说明性消息。如何在用户端显示它

我的Javascript是:

$.ajax({
    type: 'GET',
    url:  prefix + "/throwCustomized4ExceptionHandler",
    dataType: 'json',
    async: true,
    success: function(result) {
        alert('Unexpected success !!!');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status + " "
                   + textStatus + " "
               + errorThrown + " !");
    }
});

共 (2) 个答案

  1. # 1 楼答案

    我解决了以下问题:

    @ExceptionHandler(Customized4ExceptionHandler.class)
    @ResponseStatus(value=HttpStatus.BAD_REQUEST) 
    @ResponseBody
    public String handleCustomized4Exception(
        Customized4ExceptionHandler ex) {
    
        // return "zzzzzzz"
        return ex.getSpecialMsg();
    
    }
    

    $.ajax({
        type: 'GET',
        url:  prefix + "/throwCustomized4ExceptionHandler",
    
        async: true,
        success: function(result) {
            alert('Unexpected success !!!');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    }); 
    
  2. # 2 楼答案

    它应该以jqXHR.statusText的形式提供