Spring 3 exception handling using JSON

2020-03-19 02:42发布

问题:

I have a Controller and I want to get feedback to the user of what went wrong. The error callback is executed but the error message is not sent back to the client.

The JQuery call:

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;
});

The Controller:

@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;
}

The Exception Handler in the Controller:

@ExceptionHandler(Exception.class)
public @ResponseBody
String handleException(Exception e, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return e.getMessage();
}

What I want to show to the user is the String that should be returned by the handleException method. In the error callback the data parameter is undefined.