0Pricing
WebSockets & Real-Time Systems with Spring · 강의

WebSocket 오류 우아하게 처리하기

서버 측과 클라이언트 측 WebSocket 오류를 모두 처리할 수 있는 견고한 오류 처리 메커니즘을 구현합니다.

WebSocket 오류 우아하게 처리하기은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Intro to WebSocket Errors

Real-time applications, powered by WebSockets, need robust error handling. Just like any other software, things can go wrong!

Understanding and gracefully managing errors is crucial for a smooth user experience and a stable application. This lesson will cover common error types and how to handle them effectively.

Client-Side Error Types

Errors can occur on the client side (e.g., browser or mobile app) due to various reasons:

  • Network Issues: Disconnected internet, firewall blocks.
  • Server Problems: Server crash, unhandled exceptions on the server side.
  • Protocol Violations: Sending malformed data that the server rejects.
  • Client-Side Logic: Errors in processing received messages.

These often manifest as connection drops or messages failing to send/receive.

Handling Client 'onerror' Event

In JavaScript, the WebSocket API provides an onerror event listener. This event fires when a communication error occurs.

While onerror indicates a problem, it often doesn't provide detailed information. It's usually followed by an onclose event, which offers more specific status codes and reasons for the connection termination.

Client Error Handling Example

Here's how you might set up basic error and close handlers on the client side using JavaScript:

Notice how onclose provides more context with event.code and event.reason.

const ws = new WebSocket("ws://localhost:8080/my-ws");

ws.onopen = () => {
  console.log("Connected!");
};

ws.onmessage = (event) => {
  console.log(`Received: ${event.data}`);
};

ws.onerror = (error) => {
  console.error("WebSocket Error: ", error);
  // This is a generic error, often followed by onclose
};

ws.onclose = (event) => {
  if (event.wasClean) {
    console.log(`Closed cleanly, code=${event.code}, reason=${event.reason}`);
  } else {
    console.error(`Connection died, code=${event.code}, reason=${event.reason}`);
    // Handle unexpected closure, e.g., attempt reconnect
  }
};

// To trigger an error, try connecting to a non-existent port or URL.

Server-Side Error Scenarios

On the server, particularly in a Spring WebSocket application, errors can arise from:

  • Message Processing: Exceptions thrown by your @MessageMapping methods.
  • Authentication/Authorization: Security failures preventing message delivery.
  • Broker Issues: Problems connecting to or interacting with an external STOMP message broker.
  • Transport Errors: Low-level network issues or protocol violations (e.g., malformed frames).

Handling these prevents server crashes and provides meaningful feedback to clients.

Spring WebSocket Error Handling

Spring provides powerful mechanisms to manage server-side WebSocket errors:

  • @MessageExceptionHandler: For exceptions occurring during STOMP message processing in your controllers.
  • WebSocketHandlerDecoratorFactory: To intercept and handle errors related to the WebSocket connection lifecycle and transport.

These allow you to centralize error logic and respond appropriately.

Using @MessageExceptionHandler

The @MessageExceptionHandler annotation works similarly to @ExceptionHandler in REST controllers. It catches exceptions thrown by methods annotated with @MessageMapping.

You can define methods that handle specific exception types and send a custom error message back to the client, often to a dedicated error topic.

Try sending a message containing "error" to see the exception handler in action.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@SpringBootApplication
public class ErrorHandlingApp {
    public static void main(String[] args) {
        SpringApplication.run(ErrorHandlingApp.class, args);
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
}

@Controller
class ChatController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message) throws Exception {
        if (message.contains("error")) {
            throw new IllegalArgumentException("Message contains 'error' keyword!");
        }
        return "Hello, " + message + "!";
    }

    @MessageExceptionHandler
    @SendTo("/topic/errors")
    public String handleIllegalArgumentException(IllegalArgumentException ex) {
        return "Error: " + ex.getMessage();
    }
}

WebSocketHandlerDecoratorFactory

For errors outside of specific @MessageMapping methods, such as low-level transport errors or issues during connection establishment/closure, you can use a WebSocketHandlerDecoratorFactory.

This factory allows you to wrap the default WebSocketHandler with your custom logic, intercepting events like handleTransportError or afterConnectionClosed for robust logging or custom responses.

Implementing a Decorator

Here's an example of implementing a WebSocketHandlerDecoratorFactory. It wraps the standard handler to add custom logging for connection events and transport errors.

This allows you to react to issues that might not be caught by @MessageExceptionHandler, like a sudden client disconnect.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;

@SpringBootApplication
@EnableWebSocket
public class DecoratorApp implements WebSocketConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(DecoratorApp.class, args);
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/ws-decorator").setAllowedOrigins("*");
    }

    public WebSocketHandler myHandler() {
        return new TextWebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession session) throws Exception {
                System.out.println("Handler: Connection established for " + session.getId());
            }
            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
                System.out.println("Handler: Connection closed for " + session.getId() + " with status " + status);
            }
        };
    }

    @org.springframework.context.annotation.Bean
    public WebSocketHandlerDecoratorFactory decoratorFactory() {
        return (handler) -> new WebSocketHandlerDecorator(handler) {
            @Override
            public void afterConnectionEstablished(WebSocketSession session) throws Exception {
                System.out.println("Decorator: Client connected: " + session.getId());
                super.afterConnectionEstablished(session);
            }
            @Override
            public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
                System.err.println("Decorator: Transport error for session " + session.getId() + ": " + exception.getMessage());
                // You could send a generic error message to the client here if session is still open
                super.handleTransportError(session, exception);
            }
            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
                System.out.println("Decorator: Client disconnected: " + session.getId() + ", Status: " + closeStatus.getCode());
                super.afterConnectionClosed(session, closeStatus);
            }
        };
    }
}

Error Handling Best Practices

To build truly robust WebSocket applications, consider these best practices:

  • Log Everything: Use a robust logging framework (e.g., SLF4J/Logback) to capture all errors, warnings, and important events.
  • User Feedback: Provide clear, user-friendly messages on the client side when errors occur, avoiding technical jargon.
  • Graceful Degradation: If a specific feature fails, ensure the rest of the application remains functional.
  • Custom Error Messages: Never expose raw stack traces or internal server details to clients.
  • Monitoring: Implement monitoring tools to track connection health and error rates.

Error Handling Challenge

You've learned about various ways to handle WebSocket errors on both the client and server. Let's test your understanding!

Recap: Handling Errors Gracefully

In this lesson, we explored the critical topic of handling WebSocket errors. We covered:

  • Common client-side errors and how to use onerror and onclose.
  • Server-side error scenarios in Spring.
  • Utilizing @MessageExceptionHandler for STOMP message processing errors.
  • Implementing WebSocketHandlerDecoratorFactory for connection lifecycle and transport errors.
  • Key best practices for building robust, error-tolerant real-time applications.

Mastering error handling is vital for creating reliable and user-friendly WebSocket services.

자주 묻는 질문

“WebSocket 오류 우아하게 처리하기” 강의는 무료인가요?

네 — “WebSocket 오류 우아하게 처리하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

“WebSocket 오류 우아하게 처리하기”에서 뭘 배우나요?

서버 측과 클라이언트 측 WebSocket 오류를 모두 처리할 수 있는 견고한 오류 처리 메커니즘을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“WebSocket 오류 우아하게 처리하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebSocket 오류 우아하게 처리하기
  2. 연결 수명 주기 관리
  3. 재시도 및 대체 처리
  4. 하트비트 및 Ping/Pong 연결 유지
← WebSockets & Real-Time Systems with Spring(으)로 돌아가기