2011-04-12 89 views
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

回答

3

看看我的反應非常類似的問題:Spring MVC returning JSONS and exception Handling

+0

我試過,但我仍然有同樣的行爲。當拋出異常時,調用'handleException'並返回一個'HTTP 500'。在Firebug中,響應不是'JSON',而是'HTTP 500'中的'HTML'。對於HTTP 200,返回JSON。 – Sydney 2011-04-13 14:07:55

+0

編輯:當我返回一個'Response'對象時,我得到了'HTTP 406'錯誤。 – Sydney 2011-04-13 14:16:41

+0

將getters添加到'Response'類修復了'HTTP 406'錯誤。 'HTTP 500'仍然返回HTML – Sydney 2011-04-13 14:40:54