0
votes

I want test out the exception handler by doing the following:

  • send a request with an XML payload that can be unmarshalled as a valid object in my app
  • throw arbitrary error to trigger the ExceptionHandler
  • send a ServerResponse with body that is the same as ServerRequest payload

When I try to do this, I get an error on my bodyToMono(String.class) request:

Content type 'application/json' not supported for bodyType=java.lang.String

here is my Exception handler:

@Component
@Order(-2)
public class ExceptionResolver extends AbstractErrorWebExceptionHandler {

    public ExceptionResolver(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) {
        super(errorAttributes, resourceProperties, applicationContext);
        this.setMessageWriters(configurer.getWriters());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(
            ErrorAttributes errorAttributes) {
        return RouterFunctions
                .route(RequestPredicates.all(), request ->
                        request.bodyToMono(String.class).log()
                        .doOnError(e -> {
                            System.out.println("errored :(");
                            System.out.println(e.getMessage());
                        }).flatMap(r -> ServerResponse.ok().contentType(MediaType.APPLICATION_XML).syncBody(r)));
    }

What am I doing wrong? I expect that any kind of payload could be extracted as a String.class.

1

1 Answers

0
votes

I think the answer is quite simple regarding the error message. You are trying to return the response as appication/json, perhaps because you are adding content-type header to the response or because the default content type of the response is this, but you are trying to return an xml that does not fit into a json schema, and it crashes