如何改善池中的错误处理 [英] How can I improve error handling on a pool
本文介绍了如何改善池中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一个User类,它将包含将新用户插入postresql数据库的逻辑.我的代码工作正常,但我认为它编写得很差,并且希望就如何改进它(尤其是错误处理)发表一些看法.
I am have created a class User that will hold the logic for inserting a new user into a postresql database. My code works perfectly but i think it is poorly written and would like some views on how to improve it, especially error handling.
const pool = require('../config/config.js');
// user constructor
class User {
constructor(user) {
this.username = user.username;
this.email = user.email;
this.password = user.password;
this.role = user.role;
}
// save new user in databes
createUser(res) {
pool.connect((err, client, done) => {
done();
if (err) return res.status(400).json({ err });
client.query('INSERT INTO users (username, email, password, role) VALUES($1, $2, $3, $4)', [this.username, this.email, this.password, this.role], (error) => {
if (error) return res.json({ error });
return res.json({ message: 'created successfully' });
});
});
}
}
module.exports = User;
app.post('/', (req, res) => {
const user = new User({
username: 'Femoz',
password: '1234',
role: 'admin',
email: 'femoz@gmail.com',
});
user.createUser(res);
// res.json('user created successfully');
});
推荐答案
const pool = require('../config/config.js');
class User {
constructor(user) {
this.username = user.username;
this.email = user.email;
this.password = user.password;
this.role = user.role;
}
// save new user in databes
save(cb) {
const user = this;
// Perhaps, you should to do some checks of props e.g. a name is not empty
if (!user.name)
return cb(Error('Empty name'));
// I think that you should implement some wrapper
// e.g. `db.run` to avoid call the pool directly each time.
pool.connect((err, client, done) => {
// done(); here is an error. You released the db-connection too early.
if (err)
return cb(err);
// I assumed that the result of done() is undefined so cb will be called.
// Overwise use `&&` instead `||`.
client.query(
'INSERT INTO users (username, email, password, role) VALUES($1, $2, $3, $4) RETURNING id',
[user.username, user.email, user.password, user.role],
(err, res) => done() || cb(err, id: res && res.rows[0].id)
);
});
}
}
module.exports = User;
app.post('/', (req, res, next) => {
const user = new User({
username: 'Femoz',
password: '1234',
role: 'admin',
email: 'femoz@gmail.com',
});
// Return new id is better than a static text :)
user.save((err, id) => err ? res.status(400).json({error: err.message}) : res.json({id}));
// OR
// For Express you can pass error to an error handler
user.save((err, id) => err ? next(err) : res.json({id}));
});
这篇关于如何改善池中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文