在我的应用程序中,即使error instanceof NotFoundError
在每种情况下都是error
的实例,表达式NotFoundError
有时仍返回true,有时返回false。
具体地说,我有以下代码:
// apiClient.js
class HttpError {}
export class NotFoundError extends HttpError {}
export class UnauthorizedError extends HttpError {}
// Foo.jsx
import { NotFoundError } from 'apiClient';
function Foo({
errors,
...
}) {
if (errors.length > 0) {
const error = errors[0];
console.log([error, error instanceof NotFoundError]);
if (error instanceof UnauthorizedError) {
return (...);
} else if (error instanceof NotFoundError) {
return (...);
} else {
return (...);
}
}
}
我通过记录error
和error instanceof NotFoundError
的值并观察到第二个值的变化来观察这种行为。
我不知道这怎么会发生。
我在应用程序中使用Babel和Webpack,我的直觉是它们与行为有关。
instanceof
does work for subclasses of built in classes.但是NotFoundError
在继承自定义类。NotFoundError
的模块是Foo.jsx
我认为问题仍然是Webpack,但在网络上找不到与之相关的任何内容。我希望有人知道一些我不知道的“陷阱”。
这是我的webpack.config.js
:
const path = require('path');
module.exports = {
mode: 'development',
entry: {
bundle: './src/main.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
sourcePrefix: '\t'
},
module: {
rules: [
{
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
'src', 'node_modules'
] // Defining modules prevents the need for relative imports
},
};
以下是相关的编译代码:
var HttpError = function HttpError() {
_classCallCheck(this, HttpError);
};
var NotFoundError =
/*#__PURE__*/
function (_HttpError) {
_inherits(NotFoundError, _HttpError);
function NotFoundError(message) {
var _this;
_classCallCheck(this, NotFoundError);
_this = _possibleConstructorReturn(this, _getPrototypeOf(NotFoundError).call(this, message));
_this.name = "NotFoundError";
return _this;
}
return NotFoundError;
}(HttpError);
var UnauthorizedError =
/*#__PURE__*/
function (_HttpError2) {
_inherits(UnauthorizedError, _HttpError2);
function UnauthorizedError(message) {
var _this2;
_classCallCheck(this, UnauthorizedError);
_this2 = _possibleConstructorReturn(this, _getPrototypeOf(UnauthorizedError).call(this, message));
_this2.name = "UnauthorizedError";
return _this2;
}
return UnauthorizedError;
}(HttpError);
function getJson(url) {
return fetchResource(url, {
credentials: 'include'
}).then(function (response) {
if (response.ok) {
return response.json();
} else {
if (response.status === 401) {
throw new UnauthorizedError(response.body);
} else if (response.status === 404) {
throw new NotFoundError(response.body);
} else {
return response.text().then(function (text) {
throw new Error("".concat(response.status, " ").concat(text));
});
}
}
});
}
// ...
/* harmony import */ var Api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10);
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function Sidebar(_ref) {
if (profileErrors.length > 0) {
var error = profileErrors[0]; // `instanceof` does not work here because of either Babel or Webpack
if (error instanceof Api__WEBPACK_IMPORTED_MODULE_2__["UnauthorizedError"]) {
return ...;
} else if (error instanceof Api__WEBPACK_IMPORTED_MODULE_2__["NotFoundError"]) {
return ...;
} else {
return ...;
}
}
}
控制台日志: