Express js error handling

后端 未结 5 1621
无人及你
无人及你 2020-12-15 18:19

I\'m trying to get error handling running with express but instead of seeing a response of \"error!!!\" like I expect I see \"some exception\" on the console and then the pr

5条回答
  •  执念已碎
    2020-12-15 18:43

    Create an error function:

    function throwError(status, code, message) {
      const error = new Error(message);
      error.name = '';
      error.status = status;
      error.code = code;
      throw error;
    }
    

    e.g.

    throwError(422, 'InvalidEmail', '`email` should be a valid email address')
    

    We assign name to '' so that when we toString the error it doesn't prepend it with "Error: "

    As mentioned if you're using express you can create a special error handling middleware by specifying 4 arguments:

    app.use((err, req, res, next) => {
      if (err) {
        res.status(err.status || 500).json({ code: err.code || 'Error', message: err.toString() });
      }
    });
    

    If you're not using express or otherwise prefer, add that code to your catch handler instead.

    Why?

    1. Modern apps handle JSON, throwing errors in JSON makes more sense and results in cleaner UI code.

    2. You should not only throw error messages because they are imprecise to parse. What if the UI is a multilingual app? In that case they can use the code to show a localized message.

提交回复
热议问题