如何 return 来自节点应用程序的错误,以便它们被 $post.fail() 捕获
How to return errors from a node application so they are captured by $post.fail()
我有一个简单的聊天应用程序。在 index.html 中,我有一个带有 ID "nick" 输入的表单。当我提交此表单时,如果聊天室中尚不存在该用户,我想创建一个用户。如果用户确实存在(或者如果存在其他错误),我希望能够显示有用的错误消息。
这里我列出了执行此操作的 3 段代码。
我想使用 $post.fail() 处理 index.html 中用户创建过程中的任何错误。我怎样才能做到这一点?就目前而言,如果用户已经存在,Express 会在 "throw new Error('user already exists');":
行抛出以下异常
"Unhandled rejection Error: user already exists at c:\Users\Matt\Documents\code\chat\app\routes\room.js:24:19"
这是否意味着我应该在某处调用 Promise.reject()?是否有返回错误的标准方法,以便它们被 $post.fail()?
捕获
index.html
$('#myform').submit(function() {
$.post(window.location.href + 'users/create', { nickname: $('#nick').val() })
.done(function(res) {
// user created successfully
})
.fail(function() {
// user create failed
// show error message
});
return false;
});
room.js - 房间模型
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var roomSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true, index: { unique: true } },
users: [{ type: String, required: true, trim: true }]
});
module.exports = mongoose.model('Room', roomSchema);
room.js - 房间路线
var express = require('express');
var jwt = require('jsonwebtoken');
var config = require('../../config');
var Room = require('../models/room');
var router = express.Router();
router.post('/create', function(req, res) {
var promise = Room.findOne({ name: req.roomname }).exec();
promise.then(function(room) {
if (!room) {
var newRoom = Room({
name: req.roomname,
users: []
});
return newRoom.save();
}
return room;
})
.then(function(room) {
if (room.users.indexOf(req.body.nickname) > -1) {
throw new Error('user already exists');
}
room.users.push(req.body.nickname);
return room.save();
})
.then(function(room) {
var token = jwt.sign(req.body.nickname, config.secret);
return res.json({ nickname: req.body.nickname, token: token });
})
.catch(function(err) {
throw err; // I want any errors to bubble back up to the fail() in index.html so I can display a message
});
});
module.exports = router;
对于由于内部处理错误而被视为失败的请求,您应该return 5xx 作为响应状态。
.catch(function(err) {
res.status(500).json({ error: err });
});
https://www.ietf.org/rfc/rfc2616.txt
10.5 Server Error 5xx
Response status codes beginning with the digit "5" indicate cases
in which the server is aware that it has erred or is incapable of
performing the request. Except when responding to a HEAD request, the
server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition. User agents SHOULD display any included entity to the
user. These response codes are applicable to any request method.
我有一个简单的聊天应用程序。在 index.html 中,我有一个带有 ID "nick" 输入的表单。当我提交此表单时,如果聊天室中尚不存在该用户,我想创建一个用户。如果用户确实存在(或者如果存在其他错误),我希望能够显示有用的错误消息。
这里我列出了执行此操作的 3 段代码。
我想使用 $post.fail() 处理 index.html 中用户创建过程中的任何错误。我怎样才能做到这一点?就目前而言,如果用户已经存在,Express 会在 "throw new Error('user already exists');":
行抛出以下异常"Unhandled rejection Error: user already exists at c:\Users\Matt\Documents\code\chat\app\routes\room.js:24:19"
这是否意味着我应该在某处调用 Promise.reject()?是否有返回错误的标准方法,以便它们被 $post.fail()?
捕获index.html
$('#myform').submit(function() {
$.post(window.location.href + 'users/create', { nickname: $('#nick').val() })
.done(function(res) {
// user created successfully
})
.fail(function() {
// user create failed
// show error message
});
return false;
});
room.js - 房间模型
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var roomSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true, index: { unique: true } },
users: [{ type: String, required: true, trim: true }]
});
module.exports = mongoose.model('Room', roomSchema);
room.js - 房间路线
var express = require('express');
var jwt = require('jsonwebtoken');
var config = require('../../config');
var Room = require('../models/room');
var router = express.Router();
router.post('/create', function(req, res) {
var promise = Room.findOne({ name: req.roomname }).exec();
promise.then(function(room) {
if (!room) {
var newRoom = Room({
name: req.roomname,
users: []
});
return newRoom.save();
}
return room;
})
.then(function(room) {
if (room.users.indexOf(req.body.nickname) > -1) {
throw new Error('user already exists');
}
room.users.push(req.body.nickname);
return room.save();
})
.then(function(room) {
var token = jwt.sign(req.body.nickname, config.secret);
return res.json({ nickname: req.body.nickname, token: token });
})
.catch(function(err) {
throw err; // I want any errors to bubble back up to the fail() in index.html so I can display a message
});
});
module.exports = router;
对于由于内部处理错误而被视为失败的请求,您应该return 5xx 作为响应状态。
.catch(function(err) {
res.status(500).json({ error: err });
});
https://www.ietf.org/rfc/rfc2616.txt
10.5 Server Error 5xx
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of
performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition. User agents SHOULD display any included entity to the
user. These response codes are applicable to any request method.