1

这是我的控制器方法的样子:

@RequestMapping(value = "/com/uData.htm", method = RequestMethod.GET)
public @ResponseBody String getData(HttpServletRequest request, 
      HttpServletResponse response, @RequestParam(value="sn", required=true) String sn, 
      @RequestParam(value="serv", required=true) String serv,
      @RequestParam(value="date", required=false) String date) throws IOException{
try {
      Srring data =...;
      if(condition == false) {
         throw new IOException("my exception message");
    }
...
...

    } catch (IOException ie) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ie.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(ie.getMessage());
        response.flushBuffer();
    }

  return data;
}

这就是我的 jQuery ajax 的样子

$.ajax({
    cache: false,
    url: "/com/uData.htm",
    dataType: 'json',
    data: {"sn": sn, "serv": selServ},
    success: function(dt){
    result = dt;
  },
    error: function(jqXHR, textStatus, errorThrown) {
      if(jqXHR.responseText !== '') {
          alert(textStatus+": "+jqXHR.responseText);
    } else {
          alert(textStatus+": "+errorThrown);
       }  
     }
  });

返回的自定义异常消息在我的 jsp 中使用

alert(textStatus+": "+jqXHR.responseText);

如何将自定义异常消息(“我的异常消息”)返回给 JSP?

4

2 回答 2

1

将其放入您的方法的结果中。不是返回String,而是返回一个具有两个String属性的对象:resultexception

这样,客户端success代码可以检查异常。

如果您需要更多详细信息(例如异常类型或异常发生原因的其他信息),请添加更多字段。

于 2013-09-03T07:04:48.987 回答
0

尝试将 response.responseText 解析为一个对象,这样您就可以只提取 ExceptionMessage (您的自定义异常消息)。

            var message = $.parseJSON(jqXHR.responseText);
            alert(textStatus+': '+message.ExceptionMessage);

我的代码示例使用jQuery.parseJSON 方法从 JSON 中提取对象。

于 2014-05-28T22:16:51.800 回答