Skip to content

Commit

Permalink
Merge pull request #1895 from blakef/websocket-constructor-error
Browse files Browse the repository at this point in the history
fix(WebSocketSubject): pass constructor errors onto observable
  • Loading branch information
kwonoj authored Aug 24, 2016
2 parents 8b60e8d + e8bad45 commit 80b817f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
17 changes: 17 additions & 0 deletions spec/observables/dom/webSocket-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,23 @@ describe('Observable.webSocket', () => {

subject.unsubscribe();
});

it('should handle constructor errors', () => {
const subject = Observable.webSocket(<any>{
url: 'bad_url',
WebSocketCtor: (url: string, protocol?: string | string[]): WebSocket => {
throw new Error(`connection refused`);
}
});

subject.subscribe((x: any) => {
expect(x).to.equal('this should not happen');
}, (err: any) => {
expect(err).to.be.an('error', 'connection refused');
});

subject.unsubscribe();
});
});

describe('multiplex', () => {
Expand Down
19 changes: 13 additions & 6 deletions src/observable/dom/WebSocketSubject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,19 +114,26 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {

private _connectSocket() {
const { WebSocketCtor } = this;
const socket = this.protocol ?
new WebSocketCtor(this.url, this.protocol) :
new WebSocketCtor(this.url);
this.socket = socket;
const observer = this._output;

let socket: WebSocket = null;
try {
socket = this.protocol ?
new WebSocketCtor(this.url, this.protocol) :
new WebSocketCtor(this.url);
this.socket = socket;
} catch (e) {
observer.error(e);
return;
}

const subscription = new Subscription(() => {
this.socket = null;
if (socket && socket.readyState === 1) {
socket.close();
}
});

const observer = this._output;

socket.onopen = (e: Event) => {
const openObserver = this.openObserver;
if (openObserver) {
Expand Down

0 comments on commit 80b817f

Please sign in to comment.