如何将 Java 异常信息返回到 jQuery.ajax REST 调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5252573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:14:24  来源:igfitidea点击:

How to return Java Exception info to jQuery.ajax REST call?

javajqueryajax

提问by SeanLabs

I have some jQuery code that makes a REST call to a Java back end. Processing of the back end function could encounter an Exception. What is the best way to get this information back up to Javascript? In a test I caught the exception in Java and set the HTTP status code to 500. This caused the $.ajax error handler to be called, as expected. the args to the error handler don't really contain any useful information. I'd ideally like to propagate the Exception.getMessage() string back to the error handler somehow, but don't know how.

我有一些 jQuery 代码可以对 Java 后端进行 REST 调用。后端功能的处理可能会遇到异常。将此信息备份到 Javascript 的最佳方法是什么?在测试中,我在 Java 中捕获了异常并将 HTTP 状态代码设置为 500。这会导致 $.ajax 错误处理程序被调用,正如预期的那样。错误处理程序的参数并不真正包含任何有用的信息。我理想地想以某种方式将 Exception.getMessage() 字符串传播回错误处理程序,但不知道如何。


function handleClick() {
    var url = '/backend/test.json';
    $.ajax({
        type: "POST",
        url: url,
        cache: false,
        dataType: "json",
        success: function(data){
            alert("it worked");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR);
            alert(textStatus); // this comes back as "error"
            alert(errorThrown); // this comes back as "undefined"
        }
    });
}

回答by adolfo_isassi

I was able to send a custom error message (java String) back to a jQuery based client this way. I think my custom message can be replaced with the exception info you want/need

我能够以这种方式将自定义错误消息(java String)发送回基于 jQuery 的客户端。我认为我的自定义消息可以替换为您想要/需要的异常信息

in Controller:

在控制器中:

public static void handleRuntimeException(Exception ex, HttpServletResponse 
                                          response,String message) {
        logger.error(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.flushBuffer();
}

In client/javascript (called from ajax on error event)

在客户端/javascript中(在错误事件上从ajax调用)

displayError:function(jqXHR, textStatus, errorThrown){
   if(jqXHR.responseText !== ''){
        alert(textStatus+": "+jqXHR.responseText);
    }else{
        alert(textStatus+": "+errorThrown);
    }  
}

Hope this helps/

希望这可以帮助/

回答by mikerobi

Use the servlet response object's sendErrormethod, which lets you set the status code and status text message.

使用 servlet 响应对象的sendError方法,它允许您设置状态代码和状态文本消息。

Documentation

文档

ExampleEDIT

示例编辑

The jqXHRparameter gives you access to all of the response information including the status message.

jqXHR参数给你访问所有的包括状态消息的响应信息。

jqXHR.statusTextwill give you the status message passed in to the sendErrormethod.

jqXHR.statusText会给你传递给sendError方法的状态消息。

If you need more than a short message you can write data to the response output and get that from jqXHR.responseTextor jqXHR.responseXML.

如果您需要的不仅仅是一条短消息,您可以将数据写入响应输出并从jqXHR.responseText或 中获取jqXHR.responseXML