Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

javascript - 在服务/控制器层中处理Express.js中的错误(Handling errors in Express.js in service / controller layers)

I am writing an application in Express.js with a separate controller layer and a service layer.

(我正在Express.js中编写一个具有单独的控制器层和服务层的应用程序。)

Here is my current code:

(这是我当前的代码:)

user.service.js

(user.service.js)

exports.registerUser = async function (email, password) {
  const hash = await bcrypt.hash(password, 10);
  const countUser = await User.countDocuments({email: email});
  if(countUser > 0) {
    throw ({ status: 409, code: 'USER_ALREADY_EXISTS', message: 'This e-mail address is already taken.' });
  }
  const user = new User({
    email: email,
    password: hash
  });
  return await user.save();
};

exports.loginUser = async function (email, password) {
  const user = await User.findOne({ email: email });
  const countUser = await User.countDocuments({email: email});
  if(countUser === 0) {
    throw ({ status: 404, code: 'USER_NOT_EXISTS', message: 'E-mail address does not exist.' });
  }
  const validPassword = await bcrypt.compare(password, user.password);
  if (validPassword) {
    const token = jwt.sign({ email: user.email, userId: user._id }, process.env.JWT_KEY, { expiresIn: "10s" });
    return {
      token: token,
      expiresIn: 3600,
      userId: user._id
    }
  } else {
    throw ({ status: 401, code: 'LOGIN_INVALID', message: 'Invalid authentication credentials.' });
  }
};

user.controller.js

(user.controller.js)

exports.userRegister = async function (req, res, next) {
  try {
    const user = await UserService.registerUser(req.body.email, req.body.password);
    res.status(201).json({ data: user });
  } catch (e) {
    if(!e.status) {
      res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
    } else {
      res.status(e.status).json( { error: { code: e.code, message: e.message } });
    }
  }
}

exports.userLogin = async function (req, res, next) {
  try {
    const user = await UserService.loginUser(req.body.email, req.body.password);
    res.status(200).json({ data: user });
  } catch (e) {
    if(!e.status) {
      res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
    } else {
      res.status(e.status).json( { error: { code: e.code, message: e.message } });
    }
  }
}

The code works, but requires some corrections.

(该代码有效,但需要进行一些更正。)

I have a problem with error handling.

(我有一个错误处理问题。)

I want to handle only some errors.

(我只想处理一些错误。)

If another error has occurred, the 500 Internal Server Error will be returned.

(如果发生另一个错误,将返回500 Internal Server Error。)

1) Can I use "throw" object from the service layer?

(1)我可以使用服务层中的“抛出”对象吗?)

Is this a good practice?

(这是一个好习惯吗?)

2) How to avoid duplication of this code in each controller:

(2)如何避免在每个控制器中重复此代码:)

if(!e.status) {
    res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
    res.status(e.status).json( { error: { code: e.code, message: e.message } });
}

3) Does the code require other corrections?

(3)代码是否需要其他更正?)

I'm just learning Node.js and I want to write the rest of the application well.

(我只是在学习Node.js,我想很好地编写应用程序的其余部分。)

  ask by Wojtek Szymczyk translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...