Java 在生成Excel或PDF文件作为响应的REST API中,处理异常的正确方法是什么?
在生成下载文件的RESTAPI中,我们如何处理异常或错误?我有一个使用Jersey编写的API,该API生成一个Excel文件,它有适当的注释,如下所示:Java 在生成Excel或PDF文件作为响应的REST API中,处理异常的正确方法是什么?,java,rest,jersey,jax-rs,Java,Rest,Jersey,Jax Rs,在生成下载文件的RESTAPI中,我们如何处理异常或错误?我有一个使用Jersey编写的API,该API生成一个Excel文件,它有适当的注释,如下所示: @Produces("application/vnd.ms-excel") 当一切按预期进行时,我将使用文件和status.OK创建响应 但是,当发生异常时,构建响应的正确方法是什么?响应头应该是什么,@products注释会不会在提到Excel文件时引起问题,但错误响应很可能是JSON 代码段供参考: @GET @Path("{repor
@Produces("application/vnd.ms-excel")
当一切按预期进行时,我将使用文件和status.OK创建响应
但是,当发生异常时,构建响应的正确方法是什么?响应头应该是什么,@products注释会不会在提到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中异常处理的文章:
这表示您应该能够注册一个定制的ExceptionMapper,以您需要的方式处理异常响应。也许这会对您有所帮助:Thank you@Thomas,这确实是一个有用的链接。如果你可以添加它作为一个答案,我可以接受它,这可以关闭。