我正在使用FileSystemResource和Spring Webflux来提供来自硬盘驱动器的文件。
@GetMapping("/news/file")
fun getImage(@RequestParam name: String): FileSystemResource {
return FileSystemResource(propsStorage.path + "/" + name)
}当用户请求未知文件时,应捕获该文件并返回404错误。
然而,我得到了这个错误:
java.nio.file.NoSuchFileException: C:\Users\SomeUser\Work\posts\32.jpg
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 不幸的是,我不知道如何捕捉错误。如果你愿意,你可以用Java回答,我两种语言都能听懂。
发布于 2020-09-14 20:49:01
您还可以使用spring FilesystemResource api exists方法来避免FileNotFoundException
fs =FileSystemResource(propsStorage.path + "/" + name)
if(fs.exists())
return fs
else
return new ResponseEntity<>("File Not Found", HttpStatus.NOT_FOUND);我还看到你使用了'/‘作为分隔符,请注意在windows机器上文件分隔符是'’。因此,为了正确遵守,请使用Paths.separator
发布于 2020-09-14 20:30:48
您可以对java.nio.file.NoSuchFileException使用@ExceptionHandler方法,并返回404响应。
下面是Java语言,你可以用kotlin进行翻译。
@ExceptionHandler(NoSuchFileException.class)
public ResponseEntity<String> handleUnexpectedRollbackException(NoSuchFileException exception) {
LOGGER.error("File not found",exception);
return new ResponseEntity<>("File Not Found", HttpStatus.NOT_FOUND);
}https://stackoverflow.com/questions/63884242
复制相似问题