简体   繁体   English

如何获取Spring REST文件下载以返回404?

[英]How can I get a Spring REST file download to return 404?

I have a simple REST API, with file download capability. 我有一个简单的REST API,具有文件下载功能。 The endpoint is defined like this: 端点的定义如下:

@RequestMapping(value = "/myapi/files/{fileName}", 
    method = RequestMethod.GET, 
    produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ResponseBody FileSystemResource downloadFile(String fileName) 
    throws UnknownFileException;

The meat of the implementation method is currently: 当前实现方法的要点是:

try {
    FileSystemResource fsr = 
        new FileSystemResource("C:/myfiles/" + fileName + "." + suffix);
} catch (Throwable e) {
    throw new UnknownFileException();
}

And I have a simple exception handler, which returns a 404. 我有一个简单的异常处理程序,它返回404。

@ExceptionHandler(UnknownFileException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorMessage handleUnknownFileException(
        UnknownFileException e, HttpServletRequest req) {
    return new ErrorMessage(e);
}

These exception handlers work nicely for other operations which return XML/JSON responses. 这些异常处理程序可以很好地用于其他返回XML / JSON响应的操作。 The trouble I have is that when this method throws an exception, it looks like it's being intercepted by the Spring ResourceHttpMessageConverter, which is throwing a 500 error back to the client. 我遇到的麻烦是,当此方法引发异常时,它似乎被Spring ResourceHttpMessageConverter拦截,该异常将500错误返回给客户端。

So my question is how I might ensure that an HTTP 404 is returned instead of the generic 500? 所以我的问题是我如何确保返回HTTP 404而不是通用500?

Edit - Stack trace below for what it's worth: 编辑-堆栈跟踪下面的值:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.....UnknownFileException: Unable to find file
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
        org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:88)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

You probably want to do something like this: 您可能想要执行以下操作:

response.setStatus(HttpStatus.NOT_FOUND.value());

Of course, you would need to add the HttpServletResponse to the method declaration. 当然,您需要将HttpServletResponse添加到方法声明中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM