steverus_snape steverus_snape - 7 months ago 84
Node.js Question

TypeError: Object.setPrototypeOf called on null or undefined

I have a Node.js project in which I have my own custom error:

'use strict';

require('util').inherits(module.exports, Error);

function CustomError(message, extra) {
Error.captureStackTrace(this, this.constructor); =;
this.type = 'CustomError';
this.message = message;
this.extra = extra;

module.exports = CustomError;

This used to work fine. I could
Throw new CustomError('my message', dataObject)
and capture that error independently of offer error types and control the program flow accordingly.

However, since updating Node to the latest stable release (v6.4.0) it's now broken. When I run my unit tests I get the error:

TypeError: Object.setPrototypeOf called on null or undefined
at Function.setPrototypeOf (native)
at Object.exports.inherits (util.js:973:10)
at Object.<anonymous> (CustomError.js:3:17)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.require (module.js:483:17)
at require (internal/module.js:20:19)

require('util').inherits(module.exports, Error);
module.exports = CustomError;

Clearly module.exports is an empty object with an undefined .prototype in the first line. You need to call inherits after you create the constructor function! Move the line down, or use

require('util').inherits(CustomError, Error);

which would work even in the top because the function declaration is hoisted.