首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebClient - UnsupportedMediaTypeException

WebClient - UnsupportedMediaTypeException
EN

Stack Overflow用户
提问于 2021-10-14 14:55:30
回答 2查看 1.6K关注 0票数 2

我有这样的代码:

代码语言:javascript
复制
ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .retrieve()
                .toEntity(DTODemo.class)
                .block();

当我的api返回一个对象DTODemo时,它就能工作了。但是,API可以随代码HTTP404返回正文中的消息(输入字符串)。我有个例外:

代码语言:javascript
复制
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/plain;charset=UTF-8' not supported for bodyType=com.example.demo.DTODemo 

我尝试了很多事情,但我没有找到一个好的解决方案。

有什么办法解决我的问题使用检索而不是交换

非常感谢。

EN

回答 2

Stack Overflow用户

发布于 2021-10-14 18:37:18

您可以指定一组可接受的媒体类型,如接受标头所指定的。例如,

代码语言:javascript
复制
ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .toEntity(DTODemo.class)
                .block();
票数 0
EN

Stack Overflow用户

发布于 2022-10-11 22:25:45

例如,我建议创建一个自定义异常类DtoNotFoundException,并将代码包围在try/ UnsupportedMediaTypeException块中,并捕获UnsupportedMediaTypeException,然后抛出自定义异常,这样您就可以在任何其他代码中捕获它,并执行您想做的任何事情。

代码语言:javascript
复制
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Dto not found")
public class DtoNotFoundException extends RuntimeException {

    public DtoNotFoundException() {
    }

    public DtoNotFoundException(String message) {
        super(message);
    }
}

那么您的代码可以是这样的:

代码语言:javascript
复制
try{
    ResponseEntity<DTODemo> responseEntity = webClient.get()
                    .uri("http://localhost:8051/callAPI/")
                    .retrieve()
                    .toEntity(DTODemo.class)
                    .block();
}catch(UnsupportedMediaTypeException e){
    throw new DtoNotFoundException("Dto not found");
}

因此,如果您有使用代码的场景,则可以捕获自定义异常,并采取类似于返回带有异常消息的404响应代码的操作。

代码语言:javascript
复制
     @GetMapping("/dto")
    ResponseEntity<?> getDto() {
        try {
            var dtoUseExample = this.yourService.yourClientFunction() // request done;
        } catch (DtoNotFoundException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69572904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档