Skip to content

Commit

Permalink
fix(WebSocketSubject): pass constructor errors onto observable
Browse files Browse the repository at this point in the history
- Catches and passes constructor errors onto the returned observable
  • Loading branch information
Blake Friedman committed Aug 23, 2016
1 parent dd0e586 commit 49c7d67
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 49c7d67

Please sign in to comment.