我如何在Backbone.js的错误消息? [英] How do I get the error messages in Backbone.js?
问题描述
我就在Backbone.js的方法成功/错误
回调的问题。由于我是新来这个,我的问题似乎是简单的或类似的东西。
I got a question regarding success/error
callbacks of the methods in Backbone.js. As I am new to this , my question might seem to be simple or something like that.
据我所知,保存()
或取()
模型火灾方法成功
,如果没有的<em>错误的(比如除外)在服务器上。现在的问题是,我应该扔在服务器上的异常,以得到一个错误的在客户端的类型?让我给你我的意思的例子:
As far as I know, save()
or fetch()
methods of a model fires success
, if there is no error (say, exception) on the server. The question is, should I throw an exception on the server in order to get the type of an error on the client side? Let me give you an example of what I mean:
我有创建应用程序的新用户,比如在网络上的UI。我的客户端会是这个样子:
I have a UI on the web which creates a new user for the app, for instance. My client-side would look something like this:
var userView = Backbone.View.extend({
initialize:function(){ ... },
events: {
'click #sign_up': 'createAccount'
},
createAccount: function() {
login = $('#login').val();
password = $('#password').val();
var user = new User(); // User is a model
user.save({login: login, password: password},{
success: function(data) {
if (data != null) {
alert('success');
} else {
alert('fail');
}
},
error : function() {
alert('error');
}
}
});
因此,服务器端将是:
Accordingly, server side would be:
@Controller
@RequestMapping("/users")
public class UsersController {
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody User createUser(@RequestBody User user) throws Exception {
if (user == null || !user.isValid()) {
return null;// not valid - error message 1
}
if (userDao.getUserByLogin(user.getLogin()) != null) {
return null;// such user already exists! - error message 2
}
userDao.saveUser(user);
return user;
}
我想是能够相应地发送正确的错误信息是什么。如果我回到空
,那么数据的成功在
的回调将是模型,我刚刚打开填充之前发送请求。如果我抛出一个异常,那么它会火错误
。在这一点上,我应该采取什么样的方式来满足我的需求。
What I want is being able to send proper error messages accordingly. If I return null
, then the data inside success
callback will be the model that I've just populated before send the request. If I throw an exception, then it will fire error
. At this point, what approach should I take to meet my needs.
推荐答案
您不应该抛出异常。那么你可以,但你应该处理在服务器端异常,并只返回正确的HTTP codeS。
You should not throw an exception. Well you can but then you should handle the exception on the server-side and only return correct HTTP codes.
例如。
如果在服务器端没有找到用户,通常你返回404 HTTP状态code。 404将触发错误回调。
If a user is not found on the server side, normally you return a 404 HTTP Status Code. 404 will fire the error callback.
错误回调在个案多个参数,你要传递的服务器(如错误消息)上的一些数据。根据文档:
The error call back has multiple arguments in case you want to pass some data on the server (like error message). According to docs:
"error" (model, xhr, options) — when a model's save call fails on the server.
您可以在XHR对象访问的错误消息。
You can access the error message in xhr object.
这篇关于我如何在Backbone.js的错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!