What is the correct way to generate error messages that are returned in an express request?

I have a function called athat accepts a callback that is called with an error if one exists.

acalled in the express route request. If there is an error, the error should be the answer to the request.

function a(cb) {
  cb(new Error('Some error message'))
}

app.get('/', function (req, res) {
  a(function (error) {
    if (error) {
      res.json(error, 400)
    }
    res.send('No error')
  })
})

I looked at the code for Express, and it seems that res.jsonmine will be building error. However, the result of this is an empty string:

> var e = new Error('Some error message')
undefined
> JSON.stringify(e)
'{}'
> e.message
'Some error message'

, , , , toString . , , API Node, . - error , :

res.json({ error: error.message }, 400)
+6
4

Express next, , next(), , next(err).

:

app.get('/', function (req, res, next) {
  a(function (error) {
    if (error) {
      next(error);
    }
    else {
      res.send('No error')
    }
  });
});

http://expressjs.com/api.html#app.param

+1

@steveukx, , .use arity of four.

app.use(function(err, req, res, next){
  res.json(500, {
    error: err.message
  });
});

, next(err). . .

+5

, , , JSON:

function (err, data) {
    if (err) {
        res.json({
            success: false,
            error: err.message
        }, 400);
    }
    else {
        res.json({
            success: true,
            data: data
        });
    }
}

/. , node. ( , .) , , , , success.

+1
source

The correct way to throw an error is to use an informative error instead of a general error. General errors should be caused only if, for some reason, the information error itself does not work. This uses a common handler that demonstrates user errors and returns to a common error:

fpToExpressJson = async (response, next, fp, args) => {
  const oResponse = await fp(args).catch(err => err);

  if (!oResponse) {
    return next(createError(404));
  }

  if (oResponse.errorCode) {
    // Good job developer! You threw a descriptive error.
    try {
      return response.status(oResponse.errorCode).send(oResponse);
    } catch (error) {
      return next(error);
    }
  }

  return response.json(oResponse);
};
0
source

All Articles