在生成 Excel 或 PDF 文件作为响应的 REST API 中处理异常的正确方法是什么?
What is the correct way to handle exceptions in a REST API that produces an Excel or PDF file as response?
我们如何处理生成文件供下载的 REST API 中的异常或错误?我有一个使用 Jersey 编写的 API,它生成一个 Excel 文件,并且它有适当的注释:
@Produces("application/vnd.ms-excel")
当一切按预期进行时,我正在使用文件构建响应,状态为 Status.OK
。
但是,当发生异常时,构建响应的正确方法是什么?响应 header 应该是什么,@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
以您需要的方式处理异常响应。
我们如何处理生成文件供下载的 REST API 中的异常或错误?我有一个使用 Jersey 编写的 API,它生成一个 Excel 文件,并且它有适当的注释:
@Produces("application/vnd.ms-excel")
当一切按预期进行时,我正在使用文件构建响应,状态为 Status.OK
。
但是,当发生异常时,构建响应的正确方法是什么?响应 header 应该是什么,@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
以您需要的方式处理异常响应。