我尝试在JS中编写自己的HTTPError
对象。我的代码如下所示
"use strict";
HTTPError.prototype = Object.create( Error.prototype );
HTTPError.prototype.constructor = HTTPError;
function HTTPError( msg, httpStatus, httpStatusText, fileName, lineNumber ) {
var _httpStatus = httpStatus;
var _httpStatusText = httpStatusText;
// Public and privileged methods
this.httpStatus = function() {
return _httpStatus;
}
this.httpStatusText = function() {
return _httpStatusText;
}
// C'tor starts here
Error.call( this, msg, fileName, lineNumber );
this.name = "HTTPError";
}
HTTPError.prototype.toString = function() {
var name = this.name;
name = (typeof name !== "string") ? 'HTTPError' : name;
var msg = this.message;
console.log( "This is msg: " + msg );
msg = (typeof msg !== "string") ? '' : msg;
var status = '(Status: ' + this.httpStatus() + ' - ' + this.httpStatusText() + ')';
if (name === '') {
return msg + ' ' + status;
}
if (msg === '') {
return name + ' ' + status;
}
return name + ': ' + msg + ' ' + status;
}
方法toString
的灵感来自MDN Error.toString reference。 Error
- 构造函数的签名取自MDN Error reference。
问题是toString()
方法从不打印错误消息。代码行console.log( "This is msg: " + msg )
仅用于调试目的。此行显示msg
未定义,因此设置为''
。但为什么它没有定义?由于某种原因,message
属性似乎不存在,但我调用了父Error
构造函数。我做错了什么?