Skip to content

Commit

Permalink
fix(error handling): replicate pre-5.0.0 error handling (#232)
Browse files Browse the repository at this point in the history
Throw an Error if status code from HTTP is not 2XX.
  • Loading branch information
silasbw committed Mar 15, 2018
1 parent d66047e commit b5eb7e0
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/swagger-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,13 @@ class Component {
return new Promise((resolve, reject) => {
this.http.request(method, options, (err, res) => {
if (err) return reject(err);
if (res.statusCode < 200 || res.statusCode > 299) {
const error = new Error(res.body.message || res.body);
// .code is backwards compatible with pre-5.0.0 code.
error.code = res.statusCode;
error.statusCode = res.statusCode;
return reject(error);
}
resolve(res);
});
});
Expand Down
62 changes: 62 additions & 0 deletions test/swagger-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,68 @@ describe('lib.swagger-client', () => {
});
});

describe('.get', () => {
it('returns the result for 2XX', done => {
nock(common.api.url)
.get('/magic')
.reply(200, {
message: 'ta dah'
});

const options = {
config: { url: common.api.url },
spec: {
paths: {
'/magic': {
get: {
operationId: 'getMagic'
}
}
}
}
};
const client = new Client(options);
client.magic.get()
.then(res => {
assume(res.statusCode).is.equal(200);
assume(res.body.message).is.equal('ta dah');
done();
})
.catch(done);
});

it('throws an error on non-2XX', done => {
nock(common.api.url)
.get('/magic')
.reply(404, {
message: 'fail!'
});

const options = {
config: { url: common.api.url },
spec: {
paths: {
'/magic': {
get: {
operationId: 'getMagic'
}
}
}
}
};
const client = new Client(options);
client.magic.get()
.then(() => {
assume('Should not reach').is.falsy();
})
.catch(err => {
assume(err.statusCode).is.equal(404);
assume(err.message).is.equal('fail!');
done();
});
});
});

describe('.constructor', () => {
it('creates a dynamically generated client synchronously based on version', () => {
const options = { config: {}, version: '1.9' };
Expand Down

0 comments on commit b5eb7e0

Please sign in to comment.