stefanuebe/vaadin-lazy-download-button

Add support for error handling

Opened this issue · 0 comments

If createInputStream fails, it's not possible to intercept the exception and handle it.
Moreover, if setDisableOnClick is set, the button will remain disabled (because no DownloadStartsEvent will occur).

Executors.newSingleThreadExecutor().execute(() -> {
try {
InputStream inputStream = inputStreamCallback.createInputStream();
optionalUI.ifPresent(ui -> ui.access(() -> {
StreamResource href = new StreamResource(fileNameCallback.get(), () -> inputStream);
href.setCacheTime(0);
anchor.setHref(href);
anchor.getElement().callJsFunction("click");
}));
} catch (Exception e) {
throw new RuntimeException(e);
}
});

As a workaround, one need to write error handling logic inside of the InputStreamFactory:

btnDownload = new LazyDownloadButton("Download",
	() -> "foo.pdf",
	() -> {
		try {
			return new ByteArrayInputStream(generateFile());
		} catch (RuntimeException e) {
			btnDownload.getUI().ifPresent(ui->ui.access(()->{
				// restore normal state, so that the user can download the content again
				btnDownload.setText("Download");
				btnDownload.setEnabled(true);
				Notification.show("Download failed").addThemeVariants(NotificationVariant.LUMO_ERROR);
			}));
			throw e;
		}
	});