首页 > 解决方案 > `error instanceof MyError` 返回不同的值

问题描述

在我的应用程序中,表达式error instanceof NotFoundError有时返回 true,有时返回 false,即使在每种情况下error都是 的实例。NotFoundError

具体来说,我有以下代码:

// 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我通过记录and的值观察了这种行为error instanceof NotFoundError,并看到了第二个值的变化。

我不明白这怎么会发生。

我在我的应用程序中使用 Babel 和 Webpack,我的直觉是它们与行为有关。

我认为问题仍然是 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 ...;
    }
  }
}

控制台日志:

NotFoundError 日志

标签: javascriptwebpackbabeljs

解决方案


推荐阅读