I am using custom Error objects in node.js (0.8.12) with express (2.5.8). When errors occur, I want to route them to my custom error handler, but my custom Error objects are converted to Strings, while native Error objects stay the same.
Here is a simple example:
var express = require('express');var APIError = function(type) { this.type = type;}APIError.prototype = new Error();var app = express.createServer();app.use(app.router);app.use(apiErrorHandler);function log(source, err) { console.log( source, typeof err, err.constructor.name, err instanceof APIError, err instanceof Error );}function apiErrorHandler(err, req, res, next) { log("error handler:", err);}app.get('/', function(req, res, next) { var err = new APIError("notAllowed"); log("router:", err); next(err);});app.listen(80);The console output from this example is the following:
router: object Error true trueerror handler: string String false falseIf I replace new APIError("notAllowed") with new Error("notAllowed"), the object is conserved and a request produces this output:
router: object Error false trueerror handler: object Error false trueWhy is my custom Error object converted, although it is an instance of Error?