java - 在生成 Excel 或 PDF 文件作为响应的 REST API 中处理异常的正确方法是什么?
问题描述
我们如何处理生成文件供下载的 REST API 中的异常或错误?我有一个使用 Jersey 编写的 API,它生成一个 Excel 文件,它具有适当的注释:
@Produces("application/vnd.ms-excel")
当一切按预期工作时,我正在使用文件构建响应,状态为Status.OK
.
但是,发生异常时构建响应的正确方法是什么?响应头应该是什么,@Produces 注释会导致问题(因为它提到了一个 Excel 文件,但错误响应很可能是 JSON)?
代码片段供参考:
@GET
@Path("{report}")
@Produces("application/vnd.ms-excel")
public Response generateReport(@PathParam("report") String reportName /* other query params */) {
boolean isValid = false;
File file = null;
try {
/*
Logic to generate the excel file and return info about the generated report
*/
/* Includes code that throws IllegalArgumentException */
} catch(IllegalArgumentException e) {
isValid = false;
status = Status.BAD_REQUEST;
} catch(Exception e) {//Quick and dirty testing for the API
isValid = false;
status = Status.BAD_REQUEST;
}
ResponseBuilder response = null;
if(isValid) {
response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"test.xlsx\"");
} else {
response = Response.status(status);
// is this enough, or do we add info in the header here as well?
}
return response.build();
}
解决方案
根据要求,我的评论作为答案:)
这是一篇关于 JaxRS 中异常处理的文章:https ://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/part1/chapter7/exception_handling.html
这表明您应该能够注册一个自定义ExceptionMapper
,以您需要的方式处理异常响应。
推荐阅读
- jenkins - 如何使用 Groovy 集成 Jenkins 管道作业并传递动态变量?
- python - Python Jupyter Notebook Markdown - 设置水平分隔线的样式
- docker - Drone CI 无法使用私有存储库进行身份验证
- python - 如何解决错误 - python 的函数中未定义名称
- keyboard - 不能单写^
- javascript - 如何在模块公开的方法上设置监视器?
- google-sheets - Google表格:自动将新添加的单元格包含到现有公式中
- c# - 如何使用 C# Driver for MongoDB 反序列化只读字段?
- documentation - 对象签名的文档:“ ...命名参数的名称与变量名称不同”
- xamarin - Android 12.0 (S) 的 Xamarin 应用程序构建错误