我们如何处理生成下载文件的 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,以您需要的方式处理异常响应。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!