首页 > 解决方案 > 在生成 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();  
}

标签: javarestjerseyjax-rs

解决方案


根据要求,我的评论作为答案:)

这是一篇关于 JaxRS 中异常处理的文章:https ://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/part1/chapter7/exception_handling.html

这表明您应该能够注册一个自定义ExceptionMapper,以您需要的方式处理异常响应。


推荐阅读