Skip to content

Instantly share code, notes, and snippets.

@brucenunk
Created January 8, 2016 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brucenunk/ecb87ab9965932a6c61a to your computer and use it in GitHub Desktop.
Save brucenunk/ecb87ab9965932a6c61a to your computer and use it in GitHub Desktop.
Not sure how to respond to exceptions thrown when streaming Ratpack responses via Publisher.
@Grab('io.ratpack:ratpack-groovy:1.1.1')
@Grab('org.slf4j:slf4j-simple:1.7.13')
import static ratpack.groovy.Groovy.ratpack
import static ratpack.http.ResponseChunks.*
import org.reactivestreams.Subscription
import ratpack.error.ServerErrorHandler
import ratpack.handling.Context
import ratpack.render.RendererSupport
import ratpack.stream.TransformablePublisher
ratpack {
bindings {
bind ThingRenderer
bindInstance ServerErrorHandler, { context, error ->
context.response.status 500
context.render "server error = ${error}" } as ServerErrorHandler
}
handlers {
path('render-error') {
context.render(new Thing())
}
path('render-ok') {
context.render(new Thing(message: 'hello, how are you'))
}
path('streamed') {
TransformablePublisher<String> publisher = { subscriber ->
subscriber.onSubscribe(new Subscription() {
@Override
void request(long n) {
subscriber.onNext('hello\n')
subscriber.onNext('how are you')
subscriber.onError(new RuntimeException('whoops'))
}
@Override
void cancel() {
}
})
}
context.render(stringChunks('text/plain', publisher.buffer()))
}
}
}
class Thing {
String message;
}
class ThingRenderer extends RendererSupport<Thing> {
void render(Context context, Thing thing) {
if (!thing.message) {
throw new RuntimeException('thing must have message')
}
context.render(thing.message)
}
}
@brucenunk
Copy link
Author

http://localhost:5050/render-error notifies the ServerErrorHandler of the exception whereas http://localhost:5050/streamed does not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment