【问题标题】:How to return catchable error to the ajax call in Struts 2?如何将可捕获的错误返回到 Struts 2 中的 ajax 调用?
【发布时间】:2022-01-20 20:15:26
【问题描述】:

我有一些由 Ajax 调用的 Struts 2 动作。我尝试处理错误并捕获错误,但它没有按预期工作。

方法ajax方法:

deleteIndicateur(id) {
   $.ajax({
   type: "DELETE",
   url:"<%=request.getContextPath()%>/mesures.ce.delete.action?id=" + id,
   success: function (resp) {
    alert(resp);
   },
   error: function (resp) {
    alert(resp);
   }
 })
},

还有这个Action

        @Action(value = "ce.delete", results = {
                @Result(name = "success", type = "json", params = {"root", "indicateurDictionnaire"}),
                @Result(name = "error", type = "json", params = {"root", "errors"})
        })
        public String delete() {
            Integer dicId = Integer.valueOf(this.getParameter("id"));
            try {
                dicBo.delete(dicId);
            } catch (Exception e) {
                this.errors = getText(e.getMessage());
                return ERROR;
            }
            return SUCCESS;
        }

Delete 可以正常工作,但是当方法出现错误时,错误会被 ajax 请求中的成功函数捕获。我必须如何向 Ajax 返回可捕获的错误?

【问题讨论】:

    标签: ajax struts2 struts struts2-jquery


    【解决方案1】:

    如果响应具有与错误对应的状态代码,则调用回调error。见the list of HTTP status codes

    要返回带有错误消息的响应并设置错误对应的状态码需要配置操作结果error。类似于

    @Result(name = "error", type = "json", params = {"root", "errors", "statusCode", 400})
            })
    

    【讨论】:

    • 感谢 Roman,确实有效。我将它添加到参数中:params = {"root", "actionErrors", "statusCode", "400"} 现在它会出现错误,我可以从操作发送错误消息。
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多