Skip to content

Commit 49c7d67

Browse files
author
Blake Friedman
committed
fix(WebSocketSubject): pass constructor errors onto observable
- Catches and passes constructor errors onto the returned observable
1 parent dd0e586 commit 49c7d67

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

spec/observables/dom/webSocket-spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,23 @@ describe('Observable.webSocket', () => {
374374

375375
subject.unsubscribe();
376376
});
377+
378+
it('should handle constructor errors', () => {
379+
const subject = Observable.webSocket(<any>{
380+
url: 'bad_url',
381+
WebSocketCtor: (url: string, protocol?: string | string[]): WebSocket => {
382+
throw new Error(`connection refused`);
383+
}
384+
});
385+
386+
subject.subscribe((x: any) => {
387+
expect(x).to.equal('this should not happen');
388+
}, (err: any) => {
389+
expect(err).to.be.an('error', 'connection refused');
390+
});
391+
392+
subject.unsubscribe();
393+
});
377394
});
378395

379396
describe('multiplex', () => {

src/observable/dom/WebSocketSubject.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,19 +114,26 @@ export class WebSocketSubject<T> extends AnonymousSubject<T> {
114114

115115
private _connectSocket() {
116116
const { WebSocketCtor } = this;
117-
const socket = this.protocol ?
118-
new WebSocketCtor(this.url, this.protocol) :
119-
new WebSocketCtor(this.url);
120-
this.socket = socket;
117+
const observer = this._output;
118+
119+
let socket: WebSocket = null;
120+
try {
121+
socket = this.protocol ?
122+
new WebSocketCtor(this.url, this.protocol) :
123+
new WebSocketCtor(this.url);
124+
this.socket = socket;
125+
} catch (e) {
126+
observer.error(e);
127+
return;
128+
}
129+
121130
const subscription = new Subscription(() => {
122131
this.socket = null;
123132
if (socket && socket.readyState === 1) {
124133
socket.close();
125134
}
126135
});
127136

128-
const observer = this._output;
129-
130137
socket.onopen = (e: Event) => {
131138
const openObserver = this.openObserver;
132139
if (openObserver) {

0 commit comments

Comments
 (0)