Sequence.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var Util = require('util');
  2. var EventEmitter = require('events').EventEmitter;
  3. var Packets = require('../packets');
  4. var ErrorConstants = require('../constants/errors');
  5. module.exports = Sequence;
  6. Util.inherits(Sequence, EventEmitter);
  7. function Sequence(callback) {
  8. EventEmitter.call(this);
  9. this._callback = callback;
  10. this._ended = false;
  11. // Experimental: Long stack trace support
  12. this._callSite = (new Error).stack.replace(/.+\n/, '');
  13. }
  14. Sequence.determinePacket = function(byte) {
  15. switch (byte) {
  16. case 0x00: return Packets.OkPacket;
  17. case 0xfe: return Packets.EofPacket;
  18. case 0xff: return Packets.ErrorPacket;
  19. }
  20. };
  21. Sequence.prototype.hasErrorHandler = function() {
  22. return this._callback || this.listeners('error').length > 1;
  23. };
  24. Sequence.prototype._packetToError = function(packet) {
  25. var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT';
  26. var err = new Error(code + ': ' + packet.message);
  27. err.code = code;
  28. return err;
  29. };
  30. Sequence.prototype._addLongStackTrace = function(err) {
  31. var delimiter = '\n --------------------\n' ;
  32. if (err.stack.indexOf(delimiter) > -1) {
  33. return;
  34. }
  35. err.stack += delimiter + this._callSite;
  36. };
  37. Sequence.prototype.end = function(err) {
  38. if (this._ended) {
  39. return;
  40. }
  41. this._ended = true;
  42. if (err) {
  43. this._addLongStackTrace(err);
  44. }
  45. // try...finally for exception safety
  46. try {
  47. if (err) {
  48. this.emit('error', err);
  49. }
  50. } finally {
  51. try {
  52. if (this._callback) {
  53. this._callback.apply(this, arguments);
  54. }
  55. } finally {
  56. this.emit('end');
  57. }
  58. }
  59. };
  60. Sequence.prototype['OkPacket'] = function(packet) {
  61. this.end(null, packet);
  62. };
  63. Sequence.prototype['ErrorPacket'] = function(packet) {
  64. this.end(this._packetToError(packet));
  65. };
  66. // Implemented by child classes
  67. Sequence.prototype.start = function() {};