1
+ "use strict" ;
2
+ var format = require ( "util" ) . format ;
3
+
4
+ module . exports = function makeErrorFunction ( errorCodeName , errorCodeSpec ) {
5
+ if ( ! errorCodeSpec . code && errorCodeSpec . code !== 0 ) {
6
+ throw new Error ( format ( "The error code specification for %s, has no property 'code'" , errorCodeName ) ) ;
7
+ }
8
+
9
+ return function ( ) {
10
+ var error = { } , message ;
11
+ error . name = errorCodeName ;
12
+ var i = 0 ;
13
+ if ( errorCodeSpec . args ) {
14
+ for ( i = 0 ; i < errorCodeSpec . args . length ; i ++ ) {
15
+ var argName = errorCodeSpec . args [ i ] ;
16
+ if ( arguments [ i ] ) {
17
+ error [ argName ] = arguments [ i ] ;
18
+ }
19
+ }
20
+ }
21
+ if ( arguments [ i ] ) {
22
+ error . internal = arguments [ i ] ; //always allow additional last argument to be stored as internal
23
+ }
24
+ //get error message
25
+ if ( errorCodeSpec . args ) {
26
+ var formatArguments = [ errorCodeSpec . message ] ;
27
+ formatArguments . push . apply ( formatArguments , arguments ) ;
28
+ message = format . apply ( format , formatArguments ) ;
29
+ } else {
30
+ message = errorCodeSpec . message ;
31
+ }
32
+ error . message = message ;
33
+ //add additional error code spec properties
34
+ var properties = _ . keys ( errorCodeSpec ) ;
35
+ for ( i = 0 ; i < properties . length ; i ++ ) {
36
+ var propertyName = properties [ i ] ;
37
+ if ( propertyName !== "args" && propertyName !== "message" ) {
38
+ error [ propertyName ] = errorCodeSpec [ propertyName ] ;
39
+ }
40
+ }
41
+ return new Error ( JSON . stringify ( error ) ) ;
42
+ } ;
43
+ } ;
0 commit comments