1
votes

I'm using spring-webflux and I wonder if someone knows how to handle error in Mono<Void>. I'm using MultipartFile's method transferTo, which on success returns Mono.empty() and in other cases it wraps exceptions in Mono.error().

public Mono<UploadedFile> create(final User user, final FilePart file) {
    final UploadedFile uploadedFile = new UploadedFile(file.filename(), user.getId());
    final Path path = Paths.get(fileUploadConfig.getPath(), uploadedFile.getId());

    file.transferTo(path);

    uploadedFile.setFilePath(path.toString());
    return repo.save(uploadedFile);
}

I want to save UploadedFile only in case transferTo ended successfully. But I can't use map/flatMap because empty Mono obviously doesn't emit value. onErrorResume only accepts Mono with same type (Void).

1
transferTo is blocking - you probably want to use an AsnychronousFileChannel instead as in this example it is, unfortunately, more complicated than a simple method call.Michael Berry
@MichaelBerry thanks!Semyon Danilov

1 Answers

1
votes

Hi try to chain your operators like this:

    ...
    return Mono.just(file)
        .map(f -> f.transferTo(path))
        .then(Mono.just(uploadedFile))
        .flatMap(uF -> {
            uF.setFilePath(path.toString());
            return repo.save(uF)
        });
}

if your transferTo will finished successfully it calls then operators.

P.S. if I'm not mistaken FilePart is blocking, try to avoid it.