Inheriting from the Error object - where is the message property?

前端 未结 7 1233
面向向阳花
面向向阳花 2020-11-30 02:58

I noticed a strange behavior while defining custom error objects in Javascript:

function MyError(msg) {
    Error.call(this, msg);
    this.name = \"MyError\         


        
7条回答
  •  时光说笑
    2020-11-30 03:45

    I like a lot to make reusable .js files that I put in almost any project I participate. When i have time it will become a module.

    For my errors i create a exceptions.js file and add it on my files.

    Here is the example of the code inside this file:

    const util = require('util');
    
    /**
     * This exception should be used when some phat of code is not implemented.
     * @param {String} message Error message that will be used inside error.
     * @inheritDoc Error
     */
    function NotImplementedException(message) {
      this.message = message;
      Error.captureStackTrace(this, NotImplementedException);
    }
    
    util.inherits(NotImplementedException, Error);
    
    NotImplementedException.prototype.name = 'NotImplementedException';
    
    module.exports = {
      NotImplementedException,
    };
    

    In the other files of my project i must have this require line on top of the file.

    const Exceptions = require('./exceptions.js');
    

    And to use this error you just need this.

    const err = Exceptions.NotImplementedException(`Request token ${requestToken}: The "${operation}" from "${partner}" does not exist.`);
    

    Example of a full method implementation

    const notImplemented = (requestToken, operation, partner) => {
      logger.warn(`Request token ${requestToken}: To "${operation}" received from "${partner}"`);
      return new Promise((resolve, reject) => {
        const err = Exceptions.NotImplementedException(`Request token ${requestToken}: The "${operation}" from "${partner}" does not exist.`);
        logger.error(err.message);
        return reject(err);
      });
    };
    

提交回复
热议问题