我有ajax功能
$.ajax({
....
type: "POST",
url: "",
data: "",
success: function(){
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
&安培;控制器代码是
public @ResponseBody
GenericResponse abc() {
try {
....
} catch (Exception ex) {
ex.printStackTrace();
return new GenericResponse("Failed", ex.getMessage(), 500);
}
return new GenericResponse("Success", "", 200);
}
GenericResponse是
public class GenericResponse
{
private String status;
private String error;
private int code;
public GenericResponse(String s, String e, int c)
{
this.status = s;
this.error = e;
this.code = c;
}
....
}
所以成功与否失败我发送带有状态的genericresponse,但两者都进入成功回调函数。 我知道它是gennericResponse所以ajax会认为它只是成功。如果有异常 我希望它转到错误回调函数。怎么做?
答案 0 :(得分:2)
不要返回GenericResponse,而是尝试返回ResponseEntity。
你会这样做:
return new ResponseEntity<GenericResponse>(successGenericResponse, HttpStatus.OK);
或
return new ResponseEntity<GenericResponse>(failGenericResponse, HttpStatus.INTERNAL_SERVER_ERROR);