I have a simple REST API, with file download capability. 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.
@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. 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.
So my question is how I might ensure that an HTTP 404 is returned instead of the generic 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.