简体   繁体   中英

how to create an exception for an object in node.js

I'm trying to throw an exception in Node.js with an object. But I don't know how to customize the return class.

Example:


class BusinessError extends Error {
  constructor(code, status, message) {
    super(message);
    this.code = code;
    this.name = 'Error';
    this.status = status;
  }
}

const error = {
 code: '001',
 status: 500,
 message: 'Error',
}

throw new BusinessError(error.code, error.status, error.message);

But, the other attributes do not appear in the return.

Ex:

{ "message": "TypeError: foo is not a function" }

But, i wanted it to be like this

{ "message": "TypeError: foo is not a function", "code": 'X-100', "status": 500 }

Your constructor doesn't accept an object but you instantiated BusinessError with an object. You could try destructuring the object in the class constructor like so

 class BusinessError extends Error { constructor({ code, status, message }) { super(message); this.name = 'BusinessError'; this.status = status; } } const error = { code: '001', status: 500, message: 'This is an Error', } throw new BusinessError(error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM