« index

Coverage for /Users/yunong/workspace/node-restify/lib/errors/rest_error.js : 95%

92 lines | 88 run | 4 missing | 0 partial | 7 blocks | 6 blocks run | 1 blocks missing

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

  // Copyright 2012 Mark Cavage, Inc.  All rights reserved.
  
  var util = require('util');
  
  var assert = require('assert-plus');
  
  var httpErrors = require('./http_error');
  
  
  ///--- Globals
  
  var slice = Function.prototype.call.bind(Array.prototype.slice);
  
  var HttpError = httpErrors.HttpError;
  
  var CODES = {
      BadDigest: 400,
      BadMethod: 405,
      Internal: 500, // Don't have InternalErrorError
      InvalidArgument: 409,
      InvalidContent: 400,
      InvalidCredentials: 401,
      InvalidHeader: 400,
      InvalidVersion: 400,
      MissingParameter: 409,
      NotAuthorized: 403,
      PreconditionFailed: 412,
      RequestExpired: 400,
      RequestThrottled: 429,
      ResourceNotFound: 404,
      WrongAccept: 406
  };
  
  
  ///--- API
  
  function RestError(options) {
      assert.object(options, 'options');
  
      options.constructorOpt = options.constructorOpt || RestError;
      HttpError.apply(this, arguments);
  
      var self = this;
      this.restCode = options.restCode || 'Error';
      this.body = options.body || {
          code: self.restCode,
          message: options.message || self.message
      };
  }
  util.inherits(RestError, HttpError);
  
  
  ///--- Exports
  
  module.exports = {
      RestError: RestError
  };
  
  Object.keys(CODES).forEach(function (k) {
      var name = k;
      if (!/\w+Error$/.test(name))
          name += 'Error';
  
      module.exports[name] = function (cause, message) {
          var index = 1;
          var opts = {
              restCode: (k === 'Internal' ? 'InternalError' : k),
              statusCode: CODES[k]
          };
  
          opts.constructorOpt = arguments.callee;
  
          if (cause && cause instanceof Error) {
              opts.cause = cause;
          } else if (typeof (cause) === 'object') {
              opts.body = cause.body;
              opts.cause = cause.cause;
              opts.message = cause.message;
              opts.statusCode = cause.statusCode || CODES[k];
          } else {
              index = 0;
          }
  
          var args = slice(arguments, index);
          args.unshift(opts);
          RestError.apply(this, args);
      };
      util.inherits(module.exports[name], RestError);
      module.exports[name].displayName =
          module.exports[name].prototype.name =
              name;
  });
« index | cover.io