1

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?

0

2 Answers 2

1

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
    }
}, []);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.