代码之家  ›  专栏  ›  技术社区  ›  Javi

向JSON响应添加异常消息

  •  2
  • Javi  · 技术社区  · 15 年前

    我有一个代码,它抛出一个特定类型的异常,如下所示:

    throw new BadDataException("error message");
    

    这些异常是在响应类型为JSON的方法中引发的。我对此异常类型有如下配置:

    <global-exception-mappings>
         <exception-mapping result="badDataError" exception="mypackage.BadDataException" />
    </global-exception-mappings>
    
    <result name="badDataError" type="json">
        <param name="statusCode">500</param>
    </result>
    

    我想将异常消息添加到JSON响应中,以向用户显示它。当返回500状态代码时,是否有任何方法将异常消息映射到响应。Ajax调用如下所示:

    $.ajax(
    { 
       ...
        success: function(data, textStatus) {
             alert('Success'); 
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
             alert("Error");//I'd like to add here the reason (exception message)
        }
        ...
    }
    );
    

    如何将此异常的消息自动添加到HTTP 500响应中?(如果可能的话)

    谢谢

    2 回复  |  直到 15 年前
        1
  •  3
  •   Javi    15 年前

    <result name="badDataError" type="httpheader">
                    <param name="status">500</param>
                    <param name="headers.errorMessage">${exception.message}</param>
    </result>
    

    error: function (XMLHttpRequest, textStatus, errorThrown) {
         var errorMessage = XMLHttpRequest.getResponseHeader('errorMessage'); 
         ....
    }
    

        2
  •  1
  •   Steven Benitez    15 年前

    @AjaxRequest