【问题标题】:Should use custom Error object instead of default one?应该使用自定义错误对象而不是默认对象吗?
【发布时间】:2022-01-27 00:08:35
【问题描述】:

以这种方式使用默认错误对象的优缺点是什么?如果我已经可以这样使用它,我为什么要创建自定义错误对象 (class CustomError extends Error {...})?

import express from 'express';
const app = express();

// routes
app.get('/one', (req, res, next) => {
  const error = new Error();
  error.code = 400;
  error.message = 'Any error message for /one';
  next(error);
});

app.get('/two', (req, res, next) => {
// Async example
  setTimeout(() => {
    try {
      throw new Error();
    } catch (error) {
      error.code = 403;
      error.message = 'Any error message for /two';
      next(error);
    }
  }, 1000);
});

app.get('/three', (req, res, next) => {
  throw new Error('Random unexpected');
});

// error handling middlewares
app.use((error, req, res, next) => {
  console.log('ERROR LOGGER');
  console.log('Date: ', new Date(Date.now()).toLocaleString());
  console.log('Path: ', req.path);
  console.log('Status Code: ', error.code || 500);
  console.log('Message: ', error.message || 'internal server error');
  console.log('Error: ', error);
  next(error);
});
app.use((error, req, res, next) => {
  res.status(error.code || 500).json({ code: res.statusCode, message: error.message || 'internal server error' });
});

// Listen Port
app.listen(3000);

响应和日志:

/一个

/二

/三

【问题讨论】:

    标签: javascript node.js express error-handling


    【解决方案1】:

    通过创建这样一个自定义的 Error 对象

    class HttpError extends Error {
      constructor(name, code, message) {
        super();
        this.name = name;
        this.code = code;
        this.message = message;
      }
    }
    
    export default HttpError;
    

    具有集中控制和防止过度重复的优点:

    import HttpError from './HttpError.js';
    .
    .
    .
    app.get('/one', (req, res, next) => {
      next(new HttpError('Name errOne', 400, 'Any error message for /one'));
    });
    .
    .
    app.get('/two', (req, res, next) => {
    // Async example
      setTimeout(() => {
        try {
          throw new HttpError('Name errTwo', 403, 'Any error message for /two');
        } catch (error) {
          next(error);
        }
      }, 1000);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2015-10-18
      • 2015-09-21
      • 2018-05-21
      • 2018-12-10
      相关资源
      最近更新 更多