从Spring控制器抛出自定义异常并在ajax-post错误函数

时间:2017-11-27 14:38:50

标签: ajax spring error-handling

所以,我需要在我的页面添加自定义验证,问题是,我没有任何形式,我几乎手动收集和发送数据,这是我的ajax帖子:

$.ajax({
    type: "POST",
    url: "/settings/propertyedit",
    dataType: 'json',
    contentType: 'application/json;charset=UTF-8',
    data: {
            propertyName : propName,
            propertyValue : propVal,
            Id : Id,
            SettingId : SettingId,
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader($.metaCsrfHeader,  $.metaCsrfToken);
    },
    success: function (response) {
        //Do some something good
    },
    error: function(response){
        //do some something worning
    }
});

和控制器:

@Link(label = "property edit", family = "SettingsController", parent = "Settings")
@RequestMapping(value = "/settings/propertyedit", method = RequestMethod.POST)
@ResponseBody
public String atmpropertyedit(@RequestParam String propertyName,
                              @RequestParam String propertyValue,
                              @RequestParam Long Id,
                              @RequestParam Long SettingId) {
    //Check if it is an error
    //If correct i want to return some text in success function
    //If error happens want to return some relevant text to error function
}

所以,关键是,验证也是自定义的,所以我不能简单地使用try catch抛出异常,如果我想尝试做类似的事情:

return new ResponseEntity<>(HttpStatus.NOT_EXTENDED);//Error type is for testing purposes

即使没有触发我的控制器,我也会得到400错误。在这一点上,我只想要一些简单的方法让我知道我的ajax在我的控制器中发生了什么。

1 个答案:

答案 0 :(得分:0)

控制器可以像这个一样简单,你可以使用我命名为CommonResp和枚举VALIDATION的自定义响应类来实现。

控制器 - 返回响应类。

@ResponseBody
public CommonResp atmpropertyedit(@RequestParam String propertyName,
                              @RequestParam String propertyValue,
                              @RequestParam Long Id,
                              @RequestParam Long SettingId) {


        // error
        if (!isValidPropertyName(propertyName)) return new CommonResp(VALIDATION.INVALID_PROPERTY_NAME);

        // success
        return new CommonResp(VALIDATION.OK);
    }
}

CommonResp.java - 将是json响应。

public class CommonResp implements Serializable {

   private int code;
   private String message;

   public CommonResp() {
       this(VALIDATION.OK);
   }

   private CommonResp(final int code, final String message){
       this.code = code;
       this.message = message;
   }

   public CommonResp(VALIDATION validation) {
       this(validation.getCode(), validation.getMessage());
   }

    /* Getters and Setters */
}

<强> VALIDATION.java

public enum VALIDATION {

    OK(200, "OK"),
    INVALID_PROPERTY_NAME(401, "PropertyName is not valid");

    private int code;
    private  String message;

    private VALIDATION(int code, String message) {
        this.setCode(code);
        this.message = message;
    }

    /* Getters and Setters */

}

如果有更好的实施,请告诉我。 (可能是吨,只是我不知道:P)