Node.jsでカスタムエラー(メモ)
Node.jsでカスタムエラーをつくろうと思って、
Errorをinheritsしただけでは、error.stackが利用できなかったので、色々試行錯誤した結果をメモ。
ちなみに環境は
Node.js 0.10.29
// lib/error/base.js 'use strict'; var util = require('util'); function BaseError(message, code) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.status = code || 500; this.message = message || 'BaseError'; } util.inherits(BaseError, Error); module.exports = BaseError;
// lib/error/extend.js 'use strict'; var util = require('util'), BaseError = require('./base'); function ExtendError(message) { BaseError.call(this, message || 'ExtendErrorMessage'); } util.inherits(ExtendError, BaseError); module.exports = ExtendError;
// lib/sample.js var BaseError = require('./error/base'), ExtendError = require('./error/extend'); var be = new BasicError('msg1'); console.log(be); console.log(be.stack); var ee = new ExtendError('msg2', 503); console.log(ee); console.log(ee.stack);
って感じにすると
{ [BaseError: msg1] name: 'BaseError', status: 500, message: 'msg1' } BaseError: msg1 at /Users/tmarcus/Projects/node-test/lib/sample.js:4:5 : : { [ExtendError: msg2] name: 'ExtendError', status: 503, message: 'msg2' } ExtendError: msg2 at /Users/tmarcus/Projects/node-test/lib/sample.js:7:5 : :
という感じで出力されてるのでいけてるっぽい?