Passing a body to ClientErrorHandler

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Passing a body to ClientErrorHandler

Marcel
Hey!

I've a small application running which shall return status codes and possible error messages in the response.

For that the `ClientErrorHandler` interface was implemented like that:

```
public class ClientErrorHandler implements ratpack.error.ClientErrorHandler {

    public void error(Context context, int statusCode) throws Exception {

        context.getResponse()
                .contentType(HttpHeaderConstants.JSON)
                .status(statusCode).send("{\"error\": \"missing\"}");
    }
}
```

I wonder how I could set the body of the response dynamically beforehand with the context: ?

```
...
@Override
    public void handle(Context context) {
     context
                .parse(fromJson(Request.class))
                .onError(throwable -> {
                    if (throwable instanceof JsonParseException) {
                            context.clientError(HttpStatus.SC_BAD_REQUEST);
                    } else if (throwable instanceof JsonMappingException) {
                        context.clientError(HttpStatus.SC_UNPROCESSABLE_ENTITY);
                    } else {
                        context.error(throwable);
                    }
                })
...
```

Or should I call `context.getResponse` directly without passing that to the ClientErrorHandler?
Loading...