Thinking "0 RangeError:: Invalid status code" error caused by the

  Based on the recent discovery of a Node.js on the platform Express framework for running Web sites often reported such a mistake:

RangeError: Invalid status code: 0

  Source website specifically for error handling middleware, through the code after streamlined as follows:

module.exports = function (err, req, res, next) {
  var _code = err.code || 500;
  if (_code < 100 || _code >= 600) {
    _code = 500;
  }
  var _finalErr = {statusCode: -1, Message: '500 - internal server error', code: _CODE, ERR: ERR, error: to true };

  res.status(_code);
  if (!res.headersSent) {
      res.json(_finalErr);
  }

  if (err) {
    next(err);
  }
};

  At first glance, the status code here is unlikely to 0, because no matter err.code a value of 0 or a string of numbers 0, will eventually be assigned to 500. Unless the original value is a err.code not be implicitly converted into a digital string. For verification, we write the following code:

var _err = new Error();
_err.code = "illegal http status code";
throw _err;

  Start WebStorm enter debug mode, really reproduce that mistake at the beginning of this paper.

  So the question is, why a given http status code is a string, an error message is displayed here but status code is 0 then? To understand why, we find the error source stack layers. The final source of error is Node.js source writeHead function _http_server.js file, the core part of the code is as follows:

statusCode |= 0;
if (statusCode < 100 || statusCode > 999)
  throw new RangeError(`Invalid status code: ${statusCode}`);

if (common._checkInvalidHeaderChar(this.statusMessage))
  throw new Error('Invalid character in statusMessage.');

  As used herein, the javascript bitwise OR operator: |. The aim is that all non-numeric statusCode are converted to 0 by default. It can be described with reference to the following two articles to understand bitwise operators in javascript:

  http://www.w3school.com.cn/js/pro_js_operators_bitwise.asp

  https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR

  Notably, when the value involved in the calculation can not be converted implicitly to a digital result obtained at 0, with reference to some practical examples given above, the second article.

  In practice, the use of clever bitwise operators, can easily achieve the effect we want, for example, determines whether a given value is an even number, to find the nearest even number of a given value, it is determined whether a string contains in another string like.

Guess you like

Origin www.cnblogs.com/jaxu/p/11096344.html