Skip to content

Add error handling for malformed data #6

@melvincarvalho

Description

@melvincarvalho

Problem

The relay currently lacks try-catch blocks in critical areas, particularly in message processing. This could cause the relay to crash when receiving malformed data.

Areas needing error handling

1. Message parsing in websocket handler (line 36)

const [type, value, ...rest] = JSON.parse(message)

This will crash if message is not valid JSON.

2. Event validation and processing

The processMessage function doesn't handle exceptions that could occur during:

  • Event validation
  • Signature verification
  • Filter processing
  • Socket send operations

Proposed Solution

Wrap critical sections in try-catch blocks:

socket.on('message', async (message) => {
    try {
        message = message?.toString()
        console.log('received message', message)
        
        const [type, value, ...rest] = JSON.parse(message)
        await processMessage(type, value, rest, socket, events, subscribers)
    } catch (error) {
        console.error('Error processing message:', error)
        socket.send('["NOTICE", "Invalid message format"]')
    }
})

And within processMessage:

export const processMessage = async (type, value, rest, socket, events, subscribers) => {
    try {
        switch (type) {
            case 'EVENT':
                // existing code...
                break
            // other cases...
        }
    } catch (error) {
        console.error('Error in processMessage:', error)
        socket.send('["NOTICE", "Internal error processing request"]')
    }
}

Impact

  • Priority: HIGH - Prevents relay crashes
  • Complexity: Low - Simple try-catch additions
  • Mobile relevance: Critical for phone deployment where crashes are harder to recover from

Testing

  1. Send malformed JSON to the relay
  2. Send events with invalid fields
  3. Send requests with malformed filters
  4. Verify relay continues running and returns appropriate error messages

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingenhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions