Files
swift-nio/Sources/NIOWebSocket/WebSocketProtocolErrorHandler.swift
T
Cory Benfield 3803d9b096 More featureful error handling options for WebSockets (#528)
Motivation:

Currently if you hit a parse error in the WebSocketFrameDecoder, that
handler takes it upon itself to return the error code and shut the connection
down. That's not really its job: it's not a pattern that we use anywhere
else, and it prevents users from overriding this handling with their own
choices.

We should stop doing that. Unfortunately, we can't totally stop it because
it's a supported feature in the current release of NIO, but we can give
users the option to opt-out, and also build our future solution at the same
time.

Modifications:

1. Added support for disabling the automatic error handling in
    WebSocketFrameDecoder.
2. Created a new WebSocketProtocolErrorHandler class that will be used for
    default error handling in 2.0.
3. Added support to the WebSocketUpgrader to disable automatic error handling
    altogether.
4. Changed the WebSocketUpgrader to use the WebSocketProtocolErrorHandler
    for default error handling when necessary.

Result:

Better separation of concerns, and users can override NIO's default
error handling behaviour.
2018-07-31 10:27:12 +01:00

45 lines
1.7 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
/// A simple `ChannelHandler` that catches protocol errors emitted by the
/// `WebSocketFrameDecoder` and automatically generates protocol error responses.
///
/// This `ChannelHandler` provides default error handling for basic errors in the
/// WebSocket protocol, and can be used by users when custom behaviour is not required.
public final class WebSocketProtocolErrorHandler: ChannelInboundHandler {
public typealias InboundIn = Never
public typealias OutboundOut = WebSocketFrame
public init() { }
public func errorCaught(ctx: ChannelHandlerContext, error: Error) {
if let error = error as? NIOWebSocketError {
var data = ctx.channel.allocator.buffer(capacity: 2)
data.write(webSocketErrorCode: WebSocketErrorCode(error))
let frame = WebSocketFrame(fin: true,
opcode: .connectionClose,
data: data)
ctx.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete {
ctx.close(promise: nil)
}
}
// Regardless of whether this is an error we want to handle or not, we always
// forward the error on to let others see it.
ctx.fireErrorCaught(error)
}
}