json-rpc error handling (#128)

* json-rpc error handling

* partial revert
This commit is contained in:
Fabio Cigliano 2018-06-16 22:55:58 +12:00 committed by Josh Harvey
parent c3535e6ed3
commit 82726fd9c1
2 changed files with 39 additions and 16 deletions

18
dev/json-rpc.js Normal file
View file

@ -0,0 +1,18 @@
const rpc = require('../lib/plugins/common/json-rpc')
const account = {
username: 'test',
password: 'test'
}
const method = {}
const params = {
url: 'https://httpstat.us/500'
// url: 'https://httpstat.us/400'
// url: 'https://httpstat.us/200'
}
rpc.fetch(account, method, params)
.then(res => console.log('got result', res))
.catch(err => console.error('gor error', err))

View file

@ -2,32 +2,37 @@
const axios = require('axios')
const uuid = require('uuid')
const fs = require('fs')
const _ = require('lodash/fp')
module.exports = {fetch, parseConf}
function fetch (account, method, params) {
const data = {
method,
params,
id: uuid.v4()
}
return Promise.resolve(true)
.then(() => {
const data = {
method,
params,
id: uuid.v4()
}
const url = _.defaultTo(`http://localhost:${account.port}`, params.url)
return axios({
method: 'post',
auth: {username: account.username, password: account.password},
url: `http://localhost:${account.port}`,
data
})
return axios({
method: 'post',
auth: {username: account.username, password: account.password},
url,
data
})
})
.then(r => {
if (r.error) throw r.error
return r.data.result
})
.catch(err => {
console.log(err.message)
try {
console.log(err.response.data.error)
} catch (__) {}
throw err
throw new Error(_.join(' ', [
'json-rpc::axios error:',
_.get('message', err, ''),
_.get('response.data.error', err, '')
]))
})
}