M
M
minority2019-03-20 00:02:05
JavaScript
minority, 2019-03-20 00:02:05

How to process and log errors on node js (express)?

I am making api on node\express, since I came from php, the question arose of how to catch and log errors in the application correctly, depending on what it is prod\dev.
In php frameworks, the environment is easily switched and in one case only the error code (and writing to the log) in the other the entire stack trace, well, this is done centrally.
I didn’t find something like this here, I’m trying to do something like this middleware, but so far without success, tell me how it’s done correctly and whether it’s necessary.

// error handler
app.use((err, req, res, next) => {
  const error = config.isDev ? err : {};

  res.status(err.status || 500);
  res.json(error);
});

UPD
Now I have reached this method, I don’t know how much it is best practices
import User from "../models/User";

class UserController {
  index(req, res, next) {
    User.find(-1) //генерим ошибку
      .then(users => res.json(users))
      .catch(error => next({ status: 400, error }));
  }
}

The code ends up in this middleware
// error handler
app.use((err, req, res, next) => {
  const error = config.isDev ? err : {};
  
  res.status(err.status || 500);
  res.json(error);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-03-20
@Xuxicheta

Your decision is perfectly acceptable.
Although I'm used to sending the error directly in the controller method, at the end of it in the catch. It's easier to debug that way.
And different logging is implemented by its own logging functions. Which may change depending on env.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question