[英]Spring Boot - Is it possible to return a File OR xml from web service depending on success?
I've been tasked to create a web service that fetches a file from an Azure storage account. 我的任务是创建一个从Azure存储帐户中获取文件的Web服务。
On sucess : return the file as the payload 成功时 :将文件作为有效负载返回
On error : return an xml response. 错误时 :返回xml响应。
The xml response will contain a copy of the request, error codes and messages etc as the user will need a helpful error message explaining what happened. xml响应将包含请求,错误代码和消息等的副本,因为用户将需要一条有用的错误消息来解释发生了什么。
I can find instructions for how to return a single object/media type, but not multiple types dependent on condition. 我可以找到有关如何返回单个对象/媒体类型,而不是取决于条件的多种类型的说明。
Is this possible? 这可能吗?
Solved with an exception handler thanks to Abhijeet's comment - important to add the contentType or it returns JSON by default 感谢Abhijeet的注释,使用异常处理程序解决-重要的是添加contentType或默认情况下返回JSON
@ControllerAdvice
public class MyExceptionHandler {
@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
@ExceptionHandler(MyException.class)
@ResponseBody
ResponseEntity<?> exceptionHandler(MyException e){
InvoiceArchiveResponse responseObject = e.getResponseObject();
return ResponseEntity.badRequest()
.contentType(MediaType.parseMediaType("application/xml"))
.body(responseObject);
}
}
Thanks! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.