Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Read message from web socket with JavaScript

I have a web page where I receive a messages from web socket:

useEffect(() => {
            let feedAddress = "ws://.../ws_endpoint";
            
            const feedClient = new W3CWebSocket(feedAddress);
            props.onUpdateWebsocket(feedClient);
            feedClient.onopen = () => {
                console.log("WebSocket Client Connected on " + feedAddress);
            };
            feedClient.onmessage = (message) => {
                let payload = JSON.parse(message.data);
                
                // parse here the response message

            };
        }, []);

I can have 2 types of messages:

success:

{
     "requestId" : <string>,
     "response" : {
         "exchange": <string>,
         "messageId" : <string>
     }
}

error:

response: {
   "errorMessage" : <string>,
   "errorCode" : <int>
}

How I can parse both types of messages and display warning messages with the both types of responses as dialog messages?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Check for the existence of errorCode response.errorCode and conditionally process the response, since you know the structure of the responses.

Otherwise use a for...in... loop to recursively look for the string including "message" within the response object. Example on this here

about 4 years ago · Juan Pablo Isaza Report

0

I suggest using another method to catch the error case. You can do that with onerror event:

According to the MDN documentation:

The WebSocket interface's onerror event handler property is a function that gets called when an error occurs on the WebSocket.

useEffect(() => {
    let feedAddress = "ws://.../ws_endpoint";
    
    const feedClient = new W3CWebSocket(feedAddress);
    props.onUpdateWebsocket(feedClient);
    feedClient.onopen = () => {
        console.log("WebSocket Client Connected on " + feedAddress);
    };
    
    feedClient.onmessage = (message) => {
        let payload = JSON.parse(message.data);
        // do proper action on success case
    };
    
    feedClient.onerror = (error) => {
      console.log(error)
      // do proper action on failure case
    }
}, []);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!