如何处理Ajax调用和控制器之间的错误/异常

时间:2017-07-25 04:48:51

标签: ajax spring-mvc spring-boot controller

如何将错误返回给ajax然后在页面上处理此错误。

这是我的控制器代码

@RequestMapping(value = "parseMessage", method = RequestMethod.GET)
public @ResponseBody Map<String, String> parseMessage(@RequestParam("msg") String msg) {
    Map<String, String> msgParseMap = new HashMap<String, String>();
    try {
        this.messageDefinition = Utils.loadPropertiesFromClassPath("/aaa");
        this.bnsProps = Utils.loadPropertiesFromClassPath("/bbb");
        this.CntrMessageEncoding = bnsProps.getProperty("code");
        rm = new ReqMessage(this.messageDefinition, Charset.forName(this.CntrMessageEncoding),
                msg.getBytes());
        // Parse Header
        for (String header : bnsHeaderList) {
            msgParseMap.put(header,
                    rm.getFieldAsString(header, Charset.forName(this.CntrMessageEncoding)));
        }
        int position = 0;
        String restStr = msg.substring(rm.getHeaderLength());
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            int end = Integer.parseInt(entry.getValue());
            msgParseMap.put(entry.getKey(), restStr.substring(position, position + end));
            position = end;
        }
    } catch (IOException ex) {
        logger.error(ex.toString());
    }
    return msgParseMap;
}

这是我的ajax电话

$('#parseBtn').click(function(event){
            var parseMsg = $('#parseMsg').val();    
            if(parseMsg.trim().length==0){
                alert("No Data ready to Parse!");
                return;
                }
            $.ajax({
                type: "GET",
                url:  "/parseMessage",               
                data: {"msg" : parseMsg},   
                success: function (data) {                                          
                    $('#bnsHeaderTable input').each(function(){
                         var field = data[$(this).attr('id')];
                        $(this).val(field);
                    });
                    $('#txRqTable input').each(function(){
                        var field2 = data[$(this).attr('id')];
                        $(this).val(field2);
                    });
                },
                error: function(err){
                }
            });
        });

我的控制器将返回一张地图,如果有问题, 如何将代码放入ajax-error句柄部分?

谢谢

0 个答案:

没有答案