从快递服务传递错误消息

时间:2019-06-10 16:43:43

标签: node.js express

在我的节点应用程序中,我有以下代码。

import gravatar from 'gravatar';
import bcrypt from 'bcryptjs';
import config from 'config';
import jwt from 'jsonwebtoken';

import { User } from '../models/user';

class AuthService {
  /** Register user */
  async registerUser(userDto) {
    const { firstName, lastName, email, password } = userDto;

    let user = await User.findOne({ email });
    if (user) throw new Error('Email already exists');

    const avatar = this.createAvatar(email);

    user = new User({ firstName, lastName, email, password, avatar });
    user.password = await this.hashPassword(user.password);
    await user.save();

    const token = this.generateAuthToken(user);
    return { user, token }
  }

当电子邮件重复时,邮递员会给出正确的错误消息,但它是这样的。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>Error: Email already exists
            <br> &nbsp; &nbsp;at AuthService._callee$ (/home/shashika/PROJECTS/developer-connector/server/services/authService.js:14:21)
            <br> &nbsp; &nbsp;at tryCatch (/home/shashika/PROJECTS/developer-connector/server/node_modules/regenerator-runtime/runtime.js:65:40)
            <br> &nbsp; &nbsp;at Generator.invoke [as _invoke] (/home/shashika/PROJECTS/developer-connector/server/node_modules/regenerator-runtime/runtime.js:303:22)
            <br> &nbsp; &nbsp;at Generator.prototype.&lt;computed&gt; [as next] (/home/shashika/PROJECTS/developer-connector/server/node_modules/regenerator-runtime/runtime.js:117:21)
            <br> &nbsp; &nbsp;at step (/home/shashika/PROJECTS/developer-connector/server/services/authService.js:30:191)
            <br> &nbsp; &nbsp;at /home/shashika/PROJECTS/developer-connector/server/services/authService.js:30:361
            <br> &nbsp; &nbsp;at processTicksAndRejections (internal/process/task_queues.js:89:5)
        </pre>
    </body>
</html>

我只想要错误消息。但是,为什么要给我这个html代码?

3 个答案:

答案 0 :(得分:1)

您可以创建用于错误处理的全局中间件。这只是示例代码,它如何工作。只需将此中间件作为最后的中间件放置在index.js(app.js?)中即可。

errorMiddleware.js

Tag

app.js

export default (err, req, res, next) => {
    console.log('Server err', err.message);

    return res.status(err.status || 500).json({
        error: err.message
    });
};

这只是基本示例,您可以按自己的方式自定义它(仅在开发环境中发送err.message,或根据错误类型或状态等处理错误)。使用try / catch并使用express next()方法处理错误也是一种很好的方法。

答案 1 :(得分:0)

这来自快递/节点。这是一个例外,不应提供给客户端。您应该捕获错误,并使用自己的错误详细信息进行响应。

答案 2 :(得分:0)

仅在服务器内部抛出错误。您应该做的是使用适当的HTTP错误代码创建响应,然后将其发送回客户端。 假设您在其他地方捕获了错误,那么您的代码应该是这样的。如果您不告诉我们您在哪里以及如何致电registerUser。

async function user_register(req, res)
{
    try
    {
        await registerUser(param);
    }
    catch(error)
    {
        //'Email already exists' will be caught here
        // you might have multiple erors thrown here so you can use if else statements
        res.status(500); // your error code here. choose whatever you think is appropriate. you can use 'http-status-codes'
        res.json({
            message : error.message
        });
    }
}