6
我有一个Controller
,我想向用户反馈错误信息。错误回调被执行,但错误消息不会被发送回客户端。Spring 3使用JSON处理异常
jQuery的电话:
var validateButton = $('#validateSteps');
validateButton.bind('click', function() {
var stepsInput = $(':input').serializeArray();
$.postJSON('validate.htm', stepsInput, function(data) {
alert(data);
var steps = $('#steps');
var i = 0;
for(i=0;i<data.length;i++) {
steps.stepWidget('setValidationStatus', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, validationStatus: data[i].validationStatus});
steps.stepWidget('setErrorDescriptions', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, errorDescriptions: data[i].errorDescriptions});
}
return false;
}, {
error: function (XMLHttpRequest, textStatus, errorThrown, data) {
alert("error function");
alert(textStatus);
alert(errorThrown);
alert("Internal Server Error: " + data);
return false;
}
});
return false;
});
控制器:
@RequestMapping(value = "validate.htm", method = RequestMethod.POST)
public @ResponseBody
List<ValidationBean> validateSteps(
@RequestBody List<Map<String, String>> testCaseInputs,
HttpServletResponse response) throws MalformedMessageException,
MalformedProfileException, XmlException, IOException,
MissingDependencyException, MessageValidationException {
List<ValidationBean> validations = new ArrayList<ValidationBean>();
...
return validations;
}
在控制器中的异常处理程序:
@ExceptionHandler(Exception.class)
public @ResponseBody
String handleException(Exception e, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return e.getMessage();
}
我想展现给用户的是String
应该由handleException
方法返回。在error
回调中data
参数为undefined
。
我试过,但我仍然有同样的行为。当抛出异常时,调用'handleException'并返回一个'HTTP 500'。在Firebug中,响应不是'JSON',而是'HTTP 500'中的'HTML'。对于HTTP 200,返回JSON。 – Sydney 2011-04-13 14:07:55
编辑:当我返回一个'Response'对象时,我得到了'HTTP 406'错误。 – Sydney 2011-04-13 14:16:41
将getters添加到'Response'类修复了'HTTP 406'错误。 'HTTP 500'仍然返回HTML – Sydney 2011-04-13 14:40:54