简体   繁体   中英

Handle WebSocket 404 on the client side

I work on an application that uses WebSockets to stream data to the client. The way that the WebSocket endpoints are being structured ( /auth/watch/:stream-id ) it lets the browser access URLs that correspond to no stream.

The server will return a 404 error on such a case. I would like to handle such errors and display an appropriate message to the end user (eg The stream you are trying to access does not exist ).

I googled this a little bit, but was not able to find any results. Neither the Error nor the Close events of the socket provide any information about the response code (I guess this is because response codes do not make much sense with WebSockets). I found out that attempting to make an HTTP request to this endpoint results in a 404 error though, thus I could handle this with an additional request.

Is there any way though to handle such cases on the client side without an additional request ?

Thanks a lot!

Screenshot

在此处输入图片说明

You can't use a try-and-catch for this error, you'll have to determine from the close event's code, here's a sample

let ws = new WebSocket("wss://jsbin.com", "protocol");

ws.onclose = (e) => {
  if(e.code === 1006) {
    alert('ws closed abruptly');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM