PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/error.js

https://github.com/PlayNext/turtle.io
JavaScript | 51 lines | 32 code | 9 blank | 10 comment | 6 complexity | 256fdfe655aeeabe0eed57ee4e1d209a MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /**
  2. * Error handler for requests
  3. *
  4. * @method error
  5. * @param {Object} req Request Object
  6. * @param {Object} res Response Object
  7. * @param {Number} status [Optional] HTTP status code
  8. * @return {Object} TurtleIO instance
  9. */
  10. TurtleIO.prototype.error = function ( req, res, status ) {
  11. var timer = precise().start(),
  12. method = req.method.toLowerCase(),
  13. host = req.parsed ? req.parsed.hostname : ALL,
  14. kdx = -1,
  15. body, msg;
  16. if ( isNaN( status ) ) {
  17. status = this.codes.NOT_FOUND;
  18. // If valid, determine what kind of error to respond with
  19. if ( !REGEX_GET.test( method ) && !REGEX_HEAD.test( method ) ) {
  20. if ( this.allowed( method, req.url, host ) ) {
  21. status = this.codes.SERVER_ERROR;
  22. }
  23. else {
  24. status = this.codes.NOT_ALLOWED;
  25. }
  26. }
  27. }
  28. body = this.page( status, host );
  29. array.each( array.cast( this.codes ), function ( i, idx ) {
  30. if ( i === status ) {
  31. kdx = idx;
  32. return false;
  33. }
  34. } );
  35. msg = kdx ? array.cast( this.messages )[kdx] : "Unknown error";
  36. this.log( new Error( "[client " + ( req.headers["x-forwarded-for"] ? array.last( string.explode( req.headers["x-forwarded-for"] ) ) : req.connection.remoteAddress ) + "] " + msg ), "debug" );
  37. timer.stop();
  38. this.dtp.fire( "error", function () {
  39. return [req.headers.host, req.parsed.path, status, msg, timer.diff()];
  40. } );
  41. return this.respond( req, res, body, status, {"cache-control": "no-cache", "content-length": Buffer.byteLength( body )} );
  42. };