【问题标题】:JQuery can't catch exception in the Restful web serverice.JQuery 无法在 Restful Web 服务中捕获异常。
【发布时间】:2014-01-20 17:32:24
【问题描述】:

我用的是JQuery get ajax调用,在回调函数中不会捕捉到异常,在java restful代码中,我强制它抛出WebApplicationException异常,但是ajax调用捕捉不到,但是会出现在 Chrome 控制台中。

如何在 ajax 回调方法中捕获它?谢谢。

@GET
    @Path("getForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getForm() throws Exception {
    .....
        if (1==1) {
            System.out.println("---exeption ---");
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
       ....
    }

Ajax 调用

$.get('myurl', function(data, status) {
                alert(status); // not executed at all
                if (status === 'success') {
                    alert("success");
                }
                else {
                    alert("load failed");
                }
            });

在 Chrome 控制台中,我可以看到错误消息: 401 (Unauthorized) 。

【问题讨论】:

  • 您可能希望使用fail 回调来跟踪协议错误。你所拥有的只是成功回调。结帐 jquery 文档..

标签: javascript jquery exception


【解决方案1】:
$.get('myurl', function(data) {
                alert(data);

            }).fail(function(jqXHR, textStatus, errorThrown) {
   alert(jqXHR.status);
});

【讨论】:

    【解决方案2】:

    $.get中的回调函数是为了成功,你必须使用.fail来处理失败的请求。

    $.get('myurl', function(data) {
       // when success
    }).fail(function(jqXHR, textStatus, errorThrown) {
       // when fail
    });
    

    【讨论】:

    • 你能告诉我如何使用'textStatus'和'errorThrown'吗?谢谢
    猜你喜欢
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多