Skip to content
Permalink
Browse files

Talk: fixed error handling, added more error catching

  • Loading branch information...
fvdm committed Sep 24, 2012
1 parent 7f252bc commit 1d64b29d037731117204d66f2d6a0a404d6e2b93
Showing with 41 additions and 3 deletions.
  1. +41 −3 passdock.js
@@ -42,6 +42,24 @@ var app = {
}
}

// Communication error
app.buildError = function( reason, response ) {
return {
reason: reason,
response: {
headers: response.headers,
statusCode: response.statusCode,
complete: response.complete
},
request: {
method: response.req.method,
path: response.req.path,
headers: response.req._headers,
finished: response.req.finished
}
}
}

// Communicate
app.talk = function( method, path, fields, cb ) {
if( !cb && typeof fields == 'function' ) {
@@ -72,12 +90,32 @@ app.talk = function( method, path, fields, cb ) {
var data = ''
response.on( 'data', function( d ) { data += d })
response.on( 'end', function() {
if( data.match( /^(\{.*\}|\[.*\])$/ ) ) {
cb( JSON.parse( data ), true )
if( response.statusCode >= 500 ) {

// server trouble
cb( data, app.buildError( 'server error', response ))

} else if( response.statusCode >= 200 && response.statusCode < 300 ) {

// all good
if( data.match( /^(\{.*\}|\[.*\])$/ ) ) {
cb( JSON.parse( data ), false )
} else {
cb( data, app.buildError( 'invalid data', response ))
}

} else {
cb( data, false )

// API error
cb( data, app.buildError( 'error', response ))

}
})

// request cut off
response.on( 'close', function( err ) {
cb( data.toString('utf8'), {reason: 'early disconnect'} )
})
})

req.setTimeout( app.api.timeout * 60 )

0 comments on commit 1d64b29

Please sign in to comment.
You can’t perform that action at this time.