markdown Node.js中的自定义ES6错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Node.js中的自定义ES6错误相关的知识,希望对你有一定的参考价值。


Here's how you could create custom error classes in Node.js using latest ES6 / ES2015 syntax.

I've tried to make it as lean and unobtrusive as possible.

# Defining our own base class for errors

**errors/AppError.js**

```js
module.exports = class AppError extends Error {
  constructor (message, status) {
  
    // Calling parent constructor of base Error class.
    super(message);
    
    // Saving class name in the property of our custom error as a shortcut.
    this.name = this.constructor.name;

    // Capturing stack trace, excluding constructor call from it.
    Error.captureStackTrace(this, this.constructor);
    
    // You can use any additional properties you want.
    // I'm going to use preferred HTTP status for this error types.
    // `500` is the default value if not specified.
    this.status = status || 500;
    
  }
};
```

# Defining specific error types

**errors/EmailTakenError.js**

```js
module.exports = class EmailTakenError extends require('./errors/AppError') {
  constructor (message) {
    // Providing default message and overriding status code.
    super(message || 'Specified E-Mail is already taken', 400);
  }
};
```

**errors/RequestValidationError.js**

```js
module.exports = class extends require('./AppError') {
  constructor (fields) {
    // Overriding both message and status code.
    super('Request validation failed', 400);
    // Saving custom property.
    this.fields = fields || {};
  }
};
```

# Throwing and catching

```js

const AppError = require('./../api/errors/AppError');
const EmailTakenError = require('./../api/errors/EmailTakenError');
const RequestValidationError = require('./../api/errors/RequestValidationError');


try {
  // Throwing EmailTakenError exception.
  throw new EmailTakenError();
} catch (error) {
  // Catching exception by class.
  if (error instanceof EmailTakenError) {
    console.log('E-Mail validation failed!', error);
  } else {
    // If failed to catch, throwing it higher.
    console.log('Unknown error', error);
    throw error;
  }
}


try {
  // Throwing RequestValidationError exception.
  throw new RequestValidationError();
} catch (error) {
  // Catching error by base (parent) class.
  if (error instanceof AppError) {
    console.log('Some application error occurred!', error);
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}
```

# Feedback

It works great for my application, however cirtisim is welcomed.

以上是关于markdown Node.js中的自定义ES6错误的主要内容,如果未能解决你的问题,请参考以下文章

Node.js 的 commonJS 规范 ES6 导入 js 文件

带有 Express 框架的 Node.js 中的自定义事件

控制台记录时如何截断(Node)JS错误对象中的自定义字段

使用 mysql 和 node.js 的自定义前缀

node.js中的ES6变量导入名称?

Node.js 和 ES6 中的 module.exports 与 export default