From 49c7d6731170fa57d414ea050fa6de37700556c9 Mon Sep 17 00:00:00 2001 From: Blake Friedman Date: Mon, 22 Aug 2016 11:57:33 +0100 Subject: [PATCH] fix(WebSocketSubject): pass constructor errors onto observable - Catches and passes constructor errors onto the returned observable --- spec/observables/dom/webSocket-spec.ts | 17 +++++++++++++++++ src/observable/dom/WebSocketSubject.ts | 19 +++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/spec/observables/dom/webSocket-spec.ts b/spec/observables/dom/webSocket-spec.ts index b2354f558c..1e3051d538 100644 --- a/spec/observables/dom/webSocket-spec.ts +++ b/spec/observables/dom/webSocket-spec.ts @@ -374,6 +374,23 @@ describe('Observable.webSocket', () => { subject.unsubscribe(); }); + + it('should handle constructor errors', () => { + const subject = Observable.webSocket({ + 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', () => { diff --git a/src/observable/dom/WebSocketSubject.ts b/src/observable/dom/WebSocketSubject.ts index 68a4228247..b9d270a704 100644 --- a/src/observable/dom/WebSocketSubject.ts +++ b/src/observable/dom/WebSocketSubject.ts @@ -114,10 +114,19 @@ export class WebSocketSubject extends AnonymousSubject { 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) { @@ -125,8 +134,6 @@ export class WebSocketSubject extends AnonymousSubject { } }); - const observer = this._output; - socket.onopen = (e: Event) => { const openObserver = this.openObserver; if (openObserver) {