Skip to content

ResponseBodyAdvice should ignore non-match type instead throw exception [SPR-17539] #22071

Closed
@spring-projects-issues

Description

@spring-projects-issues

abccbaandy opened SPR-17539 and commented

When I use 

public class MyAdvice implements ResponseBodyAdvice<MyVo>

and my response data is

ResponseEntity<AnotherVo>

ResponseBodyAdvice will throw ClassCastException, because we can't use "supports" to check the type. It make type declare in ResponseBodyAdvice interface useless.

 

Currently, there is a workaround, use Object

ResponseBodyAdvice<Object>

and check the type in beforeBodyWrite, like this

@Override
public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (!(o instanceof MyVo)) {
        return o;
    }
    // do rest things here
}

but it doesn't look like a best practice.

 

update:

after study the source, I found there is a class cast before call beforeBodyWrite

RequestResponseBodyAdviceChain

private <T> Object processBody(@Nullable Object body, MethodParameter returnType, MediaType contentType,
      Class<? extends HttpMessageConverter<?>> converterType,
      ServerHttpRequest request, ServerHttpResponse response) {

   for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {
      if (advice.supports(returnType, converterType)) {
         body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,
               contentType, converterType, request, response);
      }
   }
   return body;
}

Can we check body is T before call beforeBodyWrite?


Affects: 5.0.9

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions