我有这样的代码:
ResponseEntity<DTODemo> responseEntity = webClient.get()
.uri("http://localhost:8051/callAPI/")
.retrieve()
.toEntity(DTODemo.class)
.block();当我的api返回一个对象DTODemo时,它就能工作了。但是,API可以随代码HTTP404返回正文中的消息(输入字符串)。我有个例外:
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/plain;charset=UTF-8' not supported for bodyType=com.example.demo.DTODemo 我尝试了很多事情,但我没有找到一个好的解决方案。
有什么办法解决我的问题使用检索而不是交换?
非常感谢。
发布于 2021-10-14 18:37:18
您可以指定一组可接受的媒体类型,如接受标头所指定的。例如,
ResponseEntity<DTODemo> responseEntity = webClient.get()
.uri("http://localhost:8051/callAPI/")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(DTODemo.class)
.block();发布于 2022-10-11 22:25:45
例如,我建议创建一个自定义异常类DtoNotFoundException,并将代码包围在try/ UnsupportedMediaTypeException块中,并捕获UnsupportedMediaTypeException,然后抛出自定义异常,这样您就可以在任何其他代码中捕获它,并执行您想做的任何事情。
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);
}
}那么您的代码可以是这样的:
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响应代码的操作。
@GetMapping("/dto")
ResponseEntity<?> getDto() {
try {
var dtoUseExample = this.yourService.yourClientFunction() // request done;
} catch (DtoNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
}
}https://stackoverflow.com/questions/69572904
复制相似问题