all files / src/ APIError.js

100% Statements 26/26
100% Branches 4/4
100% Functions 8/8
100% Lines 26/26
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              19×         74× 74× 74× 74× 74× 74× 74×                         80× 35×     45× 45×                   21×           21×       15×                      
'use strict';
 
var _ = require('underscore'),
    uuid = require('uuid/v4'),
    Class = require('class.extend'),
    APIError;
 
// Get rid of all keys in an object that have undefined values.
function filterObject(o) {
   return _.pick(o, _.identity);
}
 
module.exports = APIError = Class.extend({
 
   init: function(title, detail, status, responseBuilder) {
      this._id = uuid();
      this._title = title;
      this._detail = detail;
      this._sources = [];
      this._responseBuilder = responseBuilder;
      this.status(status);
      this.isAPIError = true;
   },
 
   /**
    * For use in chaining error creation from ResponseBuilder. ResponseBuilder, when it
    * creates an error, sets itself on the error. When you create an error through
    * ResponseBuilder, it actually returns this error. When you're done setting fields on
    * the error, you call `.rb()` to get the ResponseBuilder back.
    */
   rb: function() {
      return this._responseBuilder;
   },
 
   status: function(status) {
      if (_.isUndefined(status)) {
         return this._status;
      }
 
      this._status = status;
      return this;
   },
 
   title: function(title) {
      this._title = title;
      return this;
   },
 
   detail: function(detail) {
      this._detail = detail;
      return this;
   },
 
   addSource: function(location, path, detail, schemaPath) {
      this._sources.push({
         location: location,
         path: path,
         detail: detail,
         schemaPath: schemaPath,
      });
      return this;
   },
 
   toResponseObject: function() {
      return filterObject({
         id: this._id,
         title: this._title,
         detail: this._detail,
         status: this._status,
         sources: _.isEmpty(this._sources) ? undefined : _.map(this._sources, filterObject),
      });
   },
 
});
 
APIError.LOC_BODY = 'body';
APIError.LOC_URL = 'url';
APIError.LOC_HEADER = 'header';