Shashika Virajh
Shashika Virajh

Reputation: 9457

Passing error messages from express services

In my node application I have the following code.

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 }
  }

When there is a duplicated email, the postman gives the proper error message but its like this.

<!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>

I only want the error message. But why is this giving me this html code?

Upvotes: 1

Views: 540

Answers (3)

l2ysho
l2ysho

Reputation: 3053

You can create global middleware for error handling. This is just example code how it can work. Just place this middleware as last middleware in your index.js (app.js?).

errorMiddleware.js

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

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

app.js

import errors from './middleware/errorMiddleware';
...
// your middlewares
...
app.use(errors);

It is just basic example, you can customize it a way you want (send err.message only in dev environment, or process errors depending on error type or status and so on). It is also good approach use try/catch and handle error with express next() method.

Upvotes: 2

anegru
anegru

Reputation: 1123

The error is thrown only inside the server. What you should do is create a response with an appropriate HTTP error code and send it back to the client. Assuming you catch the error above somewhere else, your code should be something like this. If you don't show us where and how you call 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
        });
    }
}

Upvotes: 0

MattB
MattB

Reputation: 1104

This is coming from express/node. This is an exception and shouldn't be provided to the client. You should catch the error and respond with your own error details.

Upvotes: 0

Related Questions