#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Claim every coded failure the bell called unrecognised (#8115)
EthanHealy011c2359b12142
diff --git a/app/common/src/main/java/stirling/software/common/cluster/inprocess/LocalDiskFileStore.java b/app/common/src/main/java/stirling/software/common/cluster/inprocess/LocalDiskFileStore.javaindex 67ba48b4af..d278d9600a 100644--- a/app/common/src/main/java/stirling/software/common/cluster/inprocess/LocalDiskFileStore.java+++ b/app/common/src/main/java/stirling/software/common/cluster/inprocess/LocalDiskFileStore.java@@ -13,6 +13,7 @@ import java.util.regex.Pattern;import lombok.extern.slf4j.Slf4j;import stirling.software.common.cluster.FileStore;+import stirling.software.common.util.ExceptionUtils;/** Local-disk {@link FileStore} storing files under a base directory keyed by a UUID file id. */@Slf4j@@ -119,7 +120,7 @@ public class LocalDiskFileStore implements FileStore {public byte[] retrieveBytes(String fileId) throws IOException {Path filePath = resolve(fileId);if (!Files.exists(filePath)) {- throw new IOException("File not found with ID: " + fileId);+ throw ExceptionUtils.createFileNotFoundException(fileId);}return Files.readAllBytes(filePath);}@@ -128,7 +129,7 @@ public class LocalDiskFileStore implements FileStore {public long size(String fileId) throws IOException {Path filePath = resolve(fileId);if (!Files.exists(filePath)) {- throw new IOException("File not found with ID: " + fileId);+ throw ExceptionUtils.createFileNotFoundException(fileId);}return Files.size(filePath);}diff --git a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.javaindex 99d1dac96e..3e54030d5a 100644--- a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java@@ -581,14 +581,14 @@ public class ExceptionUtils {return new IOException(message, cause);}- public static IOException createImageReadException(String filename) {+ public static FileReadException createImageReadException(String filename) {requireNonNull(filename, "filename");String message =getMessage(ErrorCode.IMAGE_READ_ERROR.getMessageKey(),ErrorCode.IMAGE_READ_ERROR.getDefaultMessage(),filename);- return new IOException(message);+ return new FileReadException(message, ErrorCode.IMAGE_READ_ERROR.getCode());}/**@@ -635,25 +635,26 @@ public class ExceptionUtils {return new IllegalArgumentException(message);}- /** Create file validation exceptions. */- public static IllegalArgumentException createHtmlFileRequiredException() {+ // Coded rather than plain: a plain IllegalArgumentException reaches the handler that attaches+ // no errorCode, so the failure classifies as unrecognised even though the enum names it.+ public static FileValidationException createHtmlFileRequiredException() {String message = getMessage(ErrorCode.HTML_FILE_REQUIRED);- return new IllegalArgumentException(message);+ return new FileValidationException(message, ErrorCode.HTML_FILE_REQUIRED.getCode());}- public static IllegalArgumentException createPdfFileRequiredException() {+ public static FileValidationException createPdfFileRequiredException() {String message = getMessage(ErrorCode.PDF_NOT_PDF);- return new IllegalArgumentException(message);+ return new FileValidationException(message, ErrorCode.PDF_NOT_PDF.getCode());}- public static IllegalArgumentException createInvalidPageSizeException(String size) {+ public static StepConfigurationException createInvalidPageSizeException(String size) {requireNonNull(size, "size");String message =getMessage(ErrorCode.INVALID_PAGE_SIZE.getMessageKey(),ErrorCode.INVALID_PAGE_SIZE.getDefaultMessage(),size);- return new IllegalArgumentException(message);+ return new StepConfigurationException(message, ErrorCode.INVALID_PAGE_SIZE.getCode());}public static FileValidationException createFileNullOrEmptyException() {@@ -661,44 +662,77 @@ public class ExceptionUtils {return new FileValidationException(message, ErrorCode.FILE_NULL_OR_EMPTY.getCode());}- public static IllegalArgumentException createFileNoNameException() {+ public static FileValidationException createFileNoNameException() {String message = getMessage(ErrorCode.FILE_NO_NAME);- return new IllegalArgumentException(message);+ return new FileValidationException(message, ErrorCode.FILE_NO_NAME.getCode());}- public static IllegalArgumentException createPdfNoPages() {+ public static FileValidationException createPdfNoPages() {String message = getMessage(ErrorCode.PDF_NO_PAGES);- return new IllegalArgumentException(message);+ return new FileValidationException(message, ErrorCode.PDF_NO_PAGES.getCode());}- /** Create OCR-related exceptions. */- public static IOException createOcrLanguageRequiredException() {+ /** A stored file that an id no longer resolves to. Checked, like the reads that raise it. */+ public static FileReadException createFileNotFoundException(String fileId) {+ requireNonNull(fileId, "fileId");+ String message =+ getMessage(+ ErrorCode.FILE_NOT_FOUND.getMessageKey(),+ ErrorCode.FILE_NOT_FOUND.getDefaultMessage(),+ fileId);+ return new FileReadException(message, ErrorCode.FILE_NOT_FOUND.getCode());+ }++ public static FileReadException createFileNotFoundException(String fileId, Throwable cause) {+ requireNonNull(fileId, "fileId");+ String message =+ getMessage(+ ErrorCode.FILE_NOT_FOUND.getMessageKey(),+ ErrorCode.FILE_NOT_FOUND.getDefaultMessage(),+ fileId);+ return new FileReadException(message, cause, ErrorCode.FILE_NOT_FOUND.getCode());+ }++ // Unchecked where they were IOExceptions: a caller's bad settings are a 400, not a server+ // fault, and each is thrown before any I/O a catch could be guarding.+ public static StepConfigurationException createOcrLanguageRequiredException() {String message = getMessage(ErrorCode.OCR_LANGUAGE_REQUIRED);- return new IOException(message);+ return new StepConfigurationException(message, ErrorCode.OCR_LANGUAGE_REQUIRED.getCode());}- public static IOException createOcrInvalidLanguagesException() {+ public static StepConfigurationException createOcrInvalidLanguagesException() {String message = getMessage(ErrorCode.OCR_INVALID_LANGUAGES);- return new IOException(message);+ return new StepConfigurationException(message, ErrorCode.OCR_INVALID_LANGUAGES.getCode());}- public static IOException createOcrToolsUnavailableException() {+ public static ToolRequiredException createOcrToolsUnavailableException() {String message = getMessage(ErrorCode.OCR_TOOLS_UNAVAILABLE);- return new IOException(message);+ return new ToolRequiredException(message, ErrorCode.OCR_TOOLS_UNAVAILABLE.getCode());}- public static IOException createOcrInvalidRenderTypeException() {+ public static StepConfigurationException createOcrInvalidRenderTypeException() {String message = getMessage(ErrorCode.OCR_INVALID_RENDER_TYPE);- return new IOException(message);+ return new StepConfigurationException(message, ErrorCode.OCR_INVALID_RENDER_TYPE.getCode());}- public static IOException createOcrProcessingFailedException(int returnCode) {+ public static ToolFailedException createOcrProcessingFailedException(int returnCode) {String message =getMessage(ErrorCode.OCR_PROCESSING_FAILED.getMessageKey(),ErrorCode.OCR_PROCESSING_FAILED.getDefaultMessage(),returnCode);- return new IOException(message);+ return new ToolFailedException(message, null, ErrorCode.OCR_PROCESSING_FAILED.getCode());+ }++ public static StepConfigurationException createCompressionOptionsRequiredException() {+ String message = getMessage(ErrorCode.COMPRESSION_OPTIONS);+ return new StepConfigurationException(message, ErrorCode.COMPRESSION_OPTIONS.getCode());+ }++ public static ToolFailedException createQpdfCompressionException(IOException cause) {+ requireNonNull(cause, "cause");+ String message = getMessage(ErrorCode.QPDF_COMPRESSION);+ return new ToolFailedException(message, cause, ErrorCode.QPDF_COMPRESSION.getCode());}/**@@ -742,9 +776,19 @@ public class ExceptionUtils {return new FfmpegRequiredException(message, ErrorCode.FFMPEG_REQUIRED.getCode());}- public static IOException createPythonRequiredForWebpException() {- return createIOException(- "error.toolRequired", "{0} is required for {1}", null, "Python", "WebP conversion");+ public static ToolRequiredException createGhostscriptRequiredException(String operation) {+ requireNonNull(operation, "operation");+ String message =+ getMessage(+ ErrorCode.GHOSTSCRIPT_REQUIRED.getMessageKey(),+ ErrorCode.GHOSTSCRIPT_REQUIRED.getDefaultMessage(),+ operation);+ return new ToolRequiredException(message, ErrorCode.GHOSTSCRIPT_REQUIRED.getCode());+ }++ public static ToolRequiredException createPythonRequiredForWebpException() {+ String message = getMessage(ErrorCode.PYTHON_REQUIRED_WEBP);+ return new ToolRequiredException(message, ErrorCode.PYTHON_REQUIRED_WEBP.getCode());}/** Create compression-related exceptions. */@@ -930,17 +974,17 @@ public class ExceptionUtils {"The source file contains content Ghostscript cannot render.");}- public static IOException createGhostscriptConversionException(String outputType) {+ public static ToolFailedException createGhostscriptConversionException(String outputType) {requireNonNull(outputType, "outputType");String message =getMessage(ErrorCode.GHOSTSCRIPT_COMPRESSION.getMessageKey(),ErrorCode.GHOSTSCRIPT_COMPRESSION.getDefaultMessage(),outputType);- return new IOException(message);+ return new ToolFailedException(message, null, ErrorCode.GHOSTSCRIPT_COMPRESSION.getCode());}- public static IOException createProcessingInterruptedException(+ public static ProcessingInterruptedException createProcessingInterruptedException(String processType, InterruptedException cause) {requireNonNull(processType, "processType");requireNonNull(cause, "cause");@@ -949,15 +993,20 @@ public class ExceptionUtils {ErrorCode.PROCESSING_INTERRUPTED.getMessageKey(),ErrorCode.PROCESSING_INTERRUPTED.getDefaultMessage(),processType);- return new IOException(message, cause);+ return new ProcessingInterruptedException(message, cause);+ }++ // Checked where it was a RuntimeException: every thrower already declares throws Exception.+ public static ToolFailedException createPdfaConversionFailedException() {+ return createPdfaConversionFailedException(null);}- public static RuntimeException createPdfaConversionFailedException() {+ public static ToolFailedException createPdfaConversionFailedException(Throwable cause) {String message = getMessage(ErrorCode.PDFA_CONVERSION_FAILED);- return new RuntimeException(message);+ return new ToolFailedException(message, cause, ErrorCode.PDFA_CONVERSION_FAILED.getCode());}- public static IllegalArgumentException createInvalidArgumentException(+ public static StepConfigurationException createInvalidArgumentException(String argumentName, String value) {requireNonNull(argumentName, "argumentName");requireNonNull(value, "value");@@ -967,7 +1016,7 @@ public class ExceptionUtils {ErrorCode.INVALID_ARGUMENT.getDefaultMessage(),argumentName,value);- return new IllegalArgumentException(message);+ return new StepConfigurationException(message, ErrorCode.INVALID_ARGUMENT.getCode());}public static IllegalArgumentException createNullArgumentException(String argumentName) {@@ -1243,15 +1292,15 @@ public class ExceptionUtils {"E063","error.ffmpegRequired","FFmpeg must be installed to convert PDFs to video. Install FFmpeg and ensure it is available on the system PATH."),+ GHOSTSCRIPT_REQUIRED(+ "E064",+ "error.ghostscriptRequired",+ "Ghostscript must be installed for {0}. Install Ghostscript and ensure it is available on the system PATH."),// Validation errorsINVALID_ARGUMENT("E070", "error.invalidArgument", "Invalid argument ''{0}'': {1}"),NULL_ARGUMENT("E071", "error.nullArgument", "{0} must not be null"),INVALID_PAGE_SIZE("E072", "error.invalidPageSize", "Invalid page size format: {0}"),- INVALID_COMPARATOR(- "E073",- "error.invalidComparator",- "Invalid comparator format: only 'greater', 'equal', and 'less' are supported"),// Compliance errors. The caller builds the whole sentence: only it knows the standard,// profile and failing rules.@@ -1364,6 +1413,47 @@ public class ExceptionUtils {}}+ /**+ * A binary or runtime the step needs is absent from this deployment. Answered 503 like {@link+ * FfmpegRequiredException}: the document is fine; a retry fails until an operator installs it.+ */+ public static class ToolRequiredException extends BaseAppException {+ public ToolRequiredException(String message, String errorCode) {+ super(message, null, errorCode);+ }+ }++ /**+ * A file that cannot be read: undecodable image bytes, or a stored id that no longer resolves.+ * Stays a checked {@link IOException}, so no caller's catch changes meaning.+ */+ public static class FileReadException extends BaseAppException {+ public FileReadException(String message, String errorCode) {+ super(message, null, errorCode);+ }++ public FileReadException(String message, Throwable cause, String errorCode) {+ super(message, cause, errorCode);+ }+ }++ /**+ * A tool the step shells out to ran and did not produce a result: a non-zero exit, or no output+ * where one was promised. The document may be the cause; the tool's own output says more.+ */+ public static class ToolFailedException extends BaseAppException {+ public ToolFailedException(String message, Throwable cause, String errorCode) {+ super(message, cause, errorCode);+ }+ }++ /** The thread running a step was interrupted, so the step stopped without finishing. */+ public static class ProcessingInterruptedException extends BaseAppException {+ public ProcessingInterruptedException(String message, InterruptedException cause) {+ super(message, cause, ErrorCode.PROCESSING_INTERRUPTED.getCode());+ }+ }+private record GhostscriptErrorInfo(ErrorCode errorCode,Integer pageNumber,@@ -1427,6 +1517,16 @@ public class ExceptionUtils {}}+ /**+ * A step's settings, not its document, are unusable: a missing OCR language, a page size no+ * parser accepts. Every run of the step fails the same way until the settings change.+ */+ public static class StepConfigurationException extends BaseValidationException {+ public StepConfigurationException(String message, String errorCode) {+ super(message, errorCode);+ }+ }+/** Exception thrown when a PDF file is corrupted or damaged. */public static class PdfCorruptedException extends BaseAppException {public PdfCorruptedException(String message, Throwable cause, String errorCode) {diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.javanew file mode 100644index 0000000000..3da1683527--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java@@ -0,0 +1,120 @@+package stirling.software.common.util;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.IOException;+import java.util.function.Supplier;+import java.util.stream.Stream;++import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.MethodSource;++import stirling.software.common.util.ExceptionUtils.ErrorCodeProvider;++/**+ * Factories whose exceptions used to carry a coded message but no code. Each is pinned to its code+ * and to its supertype: the one it always had, or for the OCR settings and PDF/A ones the type a+ * bad parameter or a failed tool should have been all along.+ */+class ExceptionUtilsCodedFactoriesTest {++ static Stream<Arguments> factories() {+ return Stream.of(+ coded("E005", ExceptionUtils::createPdfNoPages, IllegalArgumentException.class),+ coded(+ "E006",+ ExceptionUtils::createPdfFileRequiredException,+ IllegalArgumentException.class),+ coded(+ "E033",+ ExceptionUtils::createFileNoNameException,+ IllegalArgumentException.class),+ coded(+ "E061",+ ExceptionUtils::createHtmlFileRequiredException,+ IllegalArgumentException.class),+ coded(+ "E034",+ () -> ExceptionUtils.createImageReadException("a.png"),+ IOException.class),+ coded(+ "E030",+ () -> ExceptionUtils.createFileNotFoundException("f-1"),+ IOException.class),+ coded(+ "E042",+ ExceptionUtils::createOcrToolsUnavailableException,+ IOException.class),+ coded(+ "E062",+ ExceptionUtils::createPythonRequiredForWebpException,+ IOException.class),+ coded(+ "E064",+ () -> ExceptionUtils.createGhostscriptRequiredException("PDF/X"),+ IOException.class),+ coded(+ "E040",+ ExceptionUtils::createOcrLanguageRequiredException,+ IllegalArgumentException.class),+ coded(+ "E041",+ ExceptionUtils::createOcrInvalidLanguagesException,+ IllegalArgumentException.class),+ coded(+ "E043",+ ExceptionUtils::createOcrInvalidRenderTypeException,+ IllegalArgumentException.class),+ coded(+ "E044",+ () -> ExceptionUtils.createOcrProcessingFailedException(2),+ IOException.class),+ coded(+ "E050",+ ExceptionUtils::createCompressionOptionsRequiredException,+ IllegalArgumentException.class),+ coded(+ "E051",+ () -> ExceptionUtils.createGhostscriptConversionException("pdf"),+ IOException.class),+ coded(+ "E052",+ () -> ExceptionUtils.createQpdfCompressionException(new IOException("x")),+ IOException.class),+ coded(+ "E053",+ () ->+ ExceptionUtils.createProcessingInterruptedException(+ "qpdf", new InterruptedException()),+ IOException.class),+ coded(+ "E060",+ ExceptionUtils::createPdfaConversionFailedException,+ IOException.class),+ coded(+ "E070",+ () -> ExceptionUtils.createInvalidArgumentException("comparator", "~"),+ IllegalArgumentException.class),+ coded(+ "E072",+ () -> ExceptionUtils.createInvalidPageSizeException("A9"),+ IllegalArgumentException.class));+ }++ private static Arguments coded(+ String code, Supplier<? extends Throwable> factory, Class<?> keptSupertype) {+ return Arguments.of(code, factory, keptSupertype);+ }++ @ParameterizedTest(name = "{0}")+ @MethodSource("factories")+ void carriesItsCodeAndKeepsItsSupertype(+ String code, Supplier<? extends Throwable> factory, Class<?> keptSupertype) {+ Throwable thrown = factory.get();++ assertThat(thrown).isInstanceOf(ErrorCodeProvider.class).isInstanceOf(keptSupertype);+ assertThat(((ErrorCodeProvider) thrown).getErrorCode()).isEqualTo(code);+ assertThat(thrown.getMessage()).isNotBlank();+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.javaindex 8268027484..2fdc200008 100644--- a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java@@ -236,7 +236,7 @@ class ExceptionUtilsGapTest {@Test@DisplayName("ocr invalid render type uses default message")void ocrInvalidRenderType() {- IOException ex = ExceptionUtils.createOcrInvalidRenderTypeException();+ IllegalArgumentException ex = ExceptionUtils.createOcrInvalidRenderTypeException();assertTrue(ex.getMessage().contains("hocr"));}diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.javaindex 4ea948b189..988dc9d532 100644--- a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java@@ -145,13 +145,13 @@ class ExceptionUtilsTest {@Testvoid testCreateOcrLanguageRequiredException() {- IOException ex = ExceptionUtils.createOcrLanguageRequiredException();+ IllegalArgumentException ex = ExceptionUtils.createOcrLanguageRequiredException();assertTrue(ex.getMessage().contains("OCR language"));}@Testvoid testCreateOcrInvalidLanguagesException() {- IOException ex = ExceptionUtils.createOcrInvalidLanguagesException();+ IllegalArgumentException ex = ExceptionUtils.createOcrInvalidLanguagesException();assertTrue(ex.getMessage().contains("none of the selected languages"));}@@ -175,7 +175,7 @@ class ExceptionUtilsTest {@Testvoid testCreatePdfaConversionFailedException() {- RuntimeException ex = ExceptionUtils.createPdfaConversionFailedException();+ IOException ex = ExceptionUtils.createPdfaConversionFailedException();assertTrue(ex.getMessage().contains("PDF/A conversion failed"));}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.javaindex 6aa8599eea..03ff8461cd 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java@@ -46,7 +46,7 @@ public class ScalePagesController {String targetPDRectangle, String orientation, PDDocument sourceDocument) {if ("KEEP".equals(targetPDRectangle)) {if (sourceDocument.getNumberOfPages() == 0) {- throw ExceptionUtils.createInvalidPageSizeException("KEEP");+ throw ExceptionUtils.createPdfNoPages();}PDPage sourcePage = sourceDocument.getPage(0);diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.javaindex 0354817315..fa55f89304 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java@@ -659,9 +659,7 @@ public class ConvertPDFToPDFA {try {// PDF/X conversion uses Ghostscript (no fallback currently)if (!isGhostscriptAvailable()) {- log.error("Ghostscript is required for PDF/X conversion");- throw new IOException(- "Ghostscript is required for PDF/X conversion but is not available on the system");+ throw ExceptionUtils.createGhostscriptRequiredException("PDF/X conversion");}log.info("Using Ghostscript for PDF/X conversion to {}", profile.getDisplayName());@@ -679,9 +677,15 @@ public class ConvertPDFToPDFA {}return WebResponseUtils.pdfFileToWebResponse(tempOut, outputFilename);- } catch (IOException | InterruptedException e) {+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw ExceptionUtils.createProcessingInterruptedException("PDF/X conversion", e);+ } catch (ExceptionUtils.BaseAppException e) {+ // Already says what went wrong, such as the missing binary above.+ throw e;+ } catch (IOException e) {log.error("PDF/X conversion failed", e);- throw ExceptionUtils.createPdfaConversionFailedException();+ throw ExceptionUtils.createPdfaConversionFailedException(e);} finally {deleteQuietly(workingDir);}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.javaindex cd2b809760..3f194f32f0 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java@@ -951,8 +951,7 @@ public class CompressController {Double lineArtThreshold = request.getLineArtThreshold();Integer lineArtEdgeLevel = request.getLineArtEdgeLevel();if (expectedOutputSizeString == null && optimizeLevel == null) {- throw ExceptionUtils.createIllegalArgumentException(- ExceptionUtils.ErrorCode.COMPRESSION_OPTIONS);+ throw ExceptionUtils.createCompressionOptionsRequiredException();}Long expectedOutputSize = 0L;@@ -1417,10 +1416,7 @@ public class CompressController {} catch (IOException e) {if (returnCode != null && returnCode.getRc() != 3) {- throw ExceptionUtils.createIOException(- ExceptionUtils.ErrorCode.QPDF_COMPRESSION.getMessageKey(),- ExceptionUtils.ErrorCode.QPDF_COMPRESSION.getDefaultMessage(),- e);+ throw ExceptionUtils.createQpdfCompressionException(e);}// If QPDF fails, keep using the current filelog.warn("QPDF compression failed, continuing with current file", e);diff --git a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.javaindex 5a80adeffe..ce06769cdf 100644--- a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java+++ b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java@@ -394,6 +394,21 @@ public class GlobalExceptionHandler {ex, HttpStatus.SERVICE_UNAVAILABLE, ErrorTypes.FFMPEG_REQUIRED, title, request);}+ /**+ * A tool or runtime the deployment lacks: the FFmpeg case generalised. 503, not 500, because+ * only the server is missing something and retries fail until it is installed.+ */+ @ExceptionHandler(ToolRequiredException.class)+ public ResponseEntity<ProblemDetail> handleToolRequired(+ ToolRequiredException ex, HttpServletRequest request) {+ logException("warn", "Required tool unavailable", request, ex, ex.getErrorCode());++ String title =+ getLocalizedMessage("error.toolRequired.title", ErrorTitles.TOOL_REQUIRED_DEFAULT);+ return createProblemDetailResponse(+ ex, HttpStatus.SERVICE_UNAVAILABLE, ErrorTypes.TOOL_REQUIRED, title, request);+ }+/*** Handle PDF and DPI-related BaseAppException subtypes.*@@ -1162,6 +1177,8 @@ public class GlobalExceptionHandler {return handleGhostscriptException((GhostscriptException) appEx, request);} else if (appEx instanceof FfmpegRequiredException) {return handleFfmpegRequired((FfmpegRequiredException) appEx, request);+ } else if (appEx instanceof ToolRequiredException toolEx) {+ return handleToolRequired(toolEx, request);} else {return handleBaseApp(appEx, request);}@@ -1462,6 +1479,7 @@ public class GlobalExceptionHandler {static final String PDF_PASSWORD = "/errors/pdf-password";static final String GHOSTSCRIPT = "/errors/ghostscript";static final String FFMPEG_REQUIRED = "/errors/ffmpeg-required";+ static final String TOOL_REQUIRED = "/errors/tool-required";static final String OUT_OF_MEMORY_DPI = "/errors/out-of-memory-dpi";static final String PDF_CORRUPTED = "/errors/pdf-corrupted";static final String PDF_ENCRYPTION = "/errors/pdf-encryption";@@ -1490,6 +1508,7 @@ public class GlobalExceptionHandler {static final String PDF_PASSWORD_DEFAULT = "PDF Password Required";static final String GHOSTSCRIPT_DEFAULT = "Ghostscript Processing Error";static final String FFMPEG_REQUIRED_DEFAULT = "FFmpeg Required";+ static final String TOOL_REQUIRED_DEFAULT = "Required Tool Not Installed";static final String OUT_OF_MEMORY_DPI_DEFAULT = "Insufficient Memory for Image Rendering";static final String PDF_CORRUPTED_DEFAULT = "PDF File Corrupted";static final String PDF_ENCRYPTION_DEFAULT = "PDF Encryption Error";diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.javaindex d56a283464..760deb45ca 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java@@ -43,6 +43,7 @@ import stirling.software.SPDF.model.api.converters.PdfToPdfARequest;import stirling.software.SPDF.service.VeraPDFService;import stirling.software.common.configuration.RuntimePathConfig;import stirling.software.common.service.PdfaLevelAServiceInterface;+import stirling.software.common.util.ExceptionUtils;import stirling.software.common.util.ProcessExecutor;import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;import stirling.software.common.util.TempFile;@@ -386,7 +387,8 @@ class ConvertPDFToPDFAMoreTest {}@Test- @DisplayName("PDF/X with Ghostscript unavailable throws the conversion-failed exception")+ @DisplayName(+ "PDF/X with Ghostscript unavailable says the tool is missing, not that conversion failed")void pdfXNoGhostscript() throws Exception {PdfToPdfARequest request = new PdfToPdfARequest();request.setFileInput(pdfFile());@@ -402,7 +404,7 @@ class ConvertPDFToPDFAMoreTest {when(executor.runCommandWithOutputHandling(any(List.class))).thenReturn(notAvail);assertThatThrownBy(() -> newController().pdfToPdfA(request))- .isInstanceOf(RuntimeException.class);+ .isInstanceOf(ExceptionUtils.ToolRequiredException.class);}}}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.javaindex 09b1bb833f..f1326fea8e 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java@@ -491,7 +491,7 @@ class OCRControllerMoreTest {request.setOcrRenderType("bogus");assertThatThrownBy(() -> ocrController.processPdfWithOCR(request))- .isInstanceOf(IOException.class);+ .isInstanceOf(IllegalArgumentException.class);verify(runtimePathConfig, never()).getTessDataPath();}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerTest.javaindex 83d036fa6e..533bc6d46b 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerTest.java@@ -165,7 +165,8 @@ class OCRControllerTest {request.setLanguages(null);request.setFileInput(pdfMultipartFile("in.pdf"));- assertThrows(IOException.class, () -> ocrController.processPdfWithOCR(request));+ assertThrows(+ IllegalArgumentException.class, () -> ocrController.processPdfWithOCR(request));// Validation happens before any tool/exec interaction.verifyNoInteractions(endpointConfiguration);}@@ -177,7 +178,8 @@ class OCRControllerTest {request.setLanguages(Collections.emptyList());request.setFileInput(pdfMultipartFile("in.pdf"));- assertThrows(IOException.class, () -> ocrController.processPdfWithOCR(request));+ assertThrows(+ IllegalArgumentException.class, () -> ocrController.processPdfWithOCR(request));verifyNoInteractions(endpointConfiguration);}@@ -188,7 +190,8 @@ class OCRControllerTest {request.setOcrRenderType("bogus");request.setFileInput(pdfMultipartFile("in.pdf"));- assertThrows(IOException.class, () -> ocrController.processPdfWithOCR(request));+ assertThrows(+ IllegalArgumentException.class, () -> ocrController.processPdfWithOCR(request));// Render-type check precedes language availability lookup.verify(runtimePathConfig, never()).getTessDataPath();}@@ -223,7 +226,8 @@ class OCRControllerTest {Path tessdata = tessdataDirWith("eng", "deu");when(runtimePathConfig.getTessDataPath()).thenReturn(tessdata.toString());- assertThrows(IOException.class, () -> ocrController.processPdfWithOCR(request));+ assertThrows(+ IllegalArgumentException.class, () -> ocrController.processPdfWithOCR(request));// Should fail before consulting tool availability.verify(endpointConfiguration, never()).isGroupEnabled(anyString());}diff --git a/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerTest.java b/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerTest.javaindex 4de6398e43..1e63034665 100644--- a/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerTest.java@@ -88,6 +88,25 @@ class GlobalExceptionHandlerTest {assertEquals(HttpStatus.SERVICE_UNAVAILABLE, resp.getStatusCode());}+ @Test+ void handleToolRequired_returns_503_with_its_code() {+ ToolRequiredException ex = new ToolRequiredException("no tesseract", "E042");+ ResponseEntity<ProblemDetail> resp = handler.handleToolRequired(ex, request);+ assertEquals(HttpStatus.SERVICE_UNAVAILABLE, resp.getStatusCode());+ assertEquals("E042", resp.getBody().getProperties().get("errorCode"));+ }++ @Test+ void handleRuntimeException_unwraps_a_wrapped_tool_required_to_503() {+ // AutoJobAspect wraps checked exceptions from a job in RuntimeException; the code and+ // status must survive that, or a folder run's failure classifies as unrecognised.+ RuntimeException wrapped =+ new RuntimeException(new ToolRequiredException("no tesseract", "E042"));+ ResponseEntity<ProblemDetail> resp = handler.handleRuntimeException(wrapped, request);+ assertEquals(HttpStatus.SERVICE_UNAVAILABLE, resp.getStatusCode());+ assertEquals("E042", resp.getBody().getProperties().get("errorCode"));+ }+// ---- PDF and DPI exceptions ----@Testdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/cluster/s3/S3FileStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/cluster/s3/S3FileStore.javaindex 68cd72ded7..a9178b82c1 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/cluster/s3/S3FileStore.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/cluster/s3/S3FileStore.java@@ -14,6 +14,7 @@ import java.util.UUID;import lombok.extern.slf4j.Slf4j;import stirling.software.common.cluster.FileStore;+import stirling.software.common.util.ExceptionUtils;import software.amazon.awssdk.core.ResponseInputStream;import software.amazon.awssdk.core.exception.SdkException;@@ -107,7 +108,7 @@ public class S3FileStore implements FileStore, AutoCloseable {ResponseInputStream<GetObjectResponse> stream = s3Client.getObject(request);return new BufferedInputStream(stream);} catch (NoSuchKeyException e) {- throw new IOException("File not found with ID: " + fileId, e);+ throw ExceptionUtils.createFileNotFoundException(fileId, e);} catch (SdkException e) {throw new IOException("Failed to load object from S3", e);}@@ -121,7 +122,7 @@ public class S3FileStore implements FileStore, AutoCloseable {try (ResponseInputStream<GetObjectResponse> stream = s3Client.getObject(request)) {return stream.readAllBytes();} catch (NoSuchKeyException e) {- throw new IOException("File not found with ID: " + fileId, e);+ throw ExceptionUtils.createFileNotFoundException(fileId, e);} catch (SdkException e) {throw new IOException("Failed to load object from S3", e);}@@ -136,10 +137,10 @@ public class S3FileStore implements FileStore, AutoCloseable {HeadObjectResponse response = s3Client.headObject(request);return Optional.ofNullable(response.contentLength()).orElse(0L);} catch (NoSuchKeyException e) {- throw new IOException("File not found with ID: " + fileId, e);+ throw ExceptionUtils.createFileNotFoundException(fileId, e);} catch (S3Exception e) {if (e.statusCode() == 404) {- throw new IOException("File not found with ID: " + fileId, e);+ throw ExceptionUtils.createFileNotFoundException(fileId, e);}throw new IOException("Failed to head object in S3", e);} catch (SdkException e) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.javaindex 605b18165a..e88a9f22b2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java@@ -166,7 +166,9 @@ public enum FailureKind {FailureSeverity.ERROR,FailureRemedy.NEEDS_SERVER_FIX,FailureScope.SERVER,- errorCodes("E042", "E062", "E063", "E080"),+ // E080 (MD5 unavailable) is deliberately not claimed: its one thrower has no throws+ // clause and its caller swallows it for a fallback hash, so it cannot reach a run.+ errorCodes("E042", "E062", "E063", "E064"),fallback("This server is missing software the step needs, so it could not be run."),// Nothing for an owner to press: their document is fine, and a retry fails the same// way until someone installs the binary.@@ -174,11 +176,8 @@ public enum FailureKind {global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),/**- * Ghostscript reached a page it could not draw, which its output names.- *- * <p>Only the recognised page-drawing failure belongs here. E051 is the bucket {@code- * ExceptionUtils.analyzeGhostscriptOutput} falls back to for output it does not recognise, so- * it also carries killed processes and full disks, which a retry does clear.+ * Ghostscript reached a page it could not draw, which its output names. Only that recognised+ * failure belongs here; the bucket Ghostscript output falls into otherwise is STEP_TOOL_FAILED.*/STEP_CANNOT_RENDER_PAGE(FailureStage.INTERNAL,@@ -193,6 +192,71 @@ public enum FailureKind {global(OPEN_IN_TOOL, OWNER, OVERFLOW),global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),+ /**+ * A tool the step shells out to ran and did not deliver: OCRmyPDF or qpdf exited non-zero,+ * LibreOffice produced no PDF/A. E051 is also the bucket unrecognised Ghostscript output falls+ * into, so it carries killed processes and full disks too; the retry offered first clears+ * those.+ */+ STEP_TOOL_FAILED(+ FailureStage.INTERNAL,+ FailureSeverity.ERROR,+ FailureRemedy.NEEDS_FILE_FIX,+ FailureScope.FILE,+ errorCodes("E044", "E051", "E052", "E060"),+ fallback("A tool this step relies on could not process this document."),+ global(OPEN_IN_TOOL, OWNER, SECONDARY),+ global(VIEW_FILE, OWNER, SECONDARY),+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),++ /** The thread running the step was interrupted: a shutdown or a cancel, not the document. */+ STEP_INTERRUPTED(+ FailureStage.INTERNAL,+ FailureSeverity.ERROR,+ FailureRemedy.TRANSIENT,+ FailureScope.FILE,+ errorCodes("E053"),+ fallback(+ "This step was stopped before it finished, so the document was not processed."),+ global(OPEN_IN_TOOL, OWNER, SECONDARY),+ global(VIEW_FILE, OWNER, SECONDARY),+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),++ /**+ * A page ran the renderer out of memory at the requested resolution. The page's size and the+ * step's DPI decide it together, so one oversized page fails while its neighbours succeed.+ */+ STEP_PAGE_TOO_LARGE(+ FailureStage.INTERNAL,+ FailureSeverity.ERROR,+ FailureRemedy.NEEDS_CONFIG_FIX,+ FailureScope.FILE,+ errorCodes("E081"),+ fallback(+ "A page in this document was too large to render at the requested resolution."),+ global(VIEW_FILE, OWNER, SECONDARY),+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),++ /**+ * The step's settings, not the document, were refused: no OCR language, an unparseable page+ * size. Scoped to the policy, since every document it reaches fails identically until the step+ * is edited, and one incident says that best.+ */+ STEP_MISCONFIGURED(+ FailureStage.INTERNAL,+ FailureSeverity.ERROR,+ FailureRemedy.NEEDS_CONFIG_FIX,+ FailureScope.POLICY,+ errorCodes("E040", "E041", "E043", "E050", "E070", "E072"),+ fallback("This step's settings are not valid, so it could not run."),+ // Nothing for an owner to press: their document is fine, and only whoever can edit the+ // policy can change the settings.+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, SECONDARY),+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),+UNKNOWN(FailureStage.INTERNAL,FailureSeverity.ERROR,diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/ClaimedErrorCodesAreEmittableTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/ClaimedErrorCodesAreEmittableTest.javanew file mode 100644index 0000000000..48af0f54ca--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/ClaimedErrorCodesAreEmittableTest.java@@ -0,0 +1,137 @@+package stirling.software.proprietary.failure;++import static org.assertj.core.api.Assertions.assertThat;++import java.lang.reflect.Method;+import java.lang.reflect.Modifier;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.function.Supplier;++import org.junit.jupiter.api.Test;++import stirling.software.common.util.ExceptionUtils;+import stirling.software.common.util.ExceptionUtils.ErrorCode;+import stirling.software.common.util.ExceptionUtils.ErrorCodeProvider;++/**+ * Every code a kind claims must come out of some {@link ExceptionUtils} factory as an {@link+ * ErrorCodeProvider}: a plain exception with the code's message reaches a handler that adds none.+ */+class ClaimedErrorCodesAreEmittableTest {++ /**+ * Codes a factory only produces for particular input, which the type-default arguments below+ * cannot supply. Each names the input that selects the code, so the entry is itself the proof.+ */+ private static final Map<String, Supplier<Throwable>> SELECTED_BY_CONTENT =+ Map.of(+ // GHOSTSCRIPT_PAGE_DRAWING is recognised from the tool's output, not chosen.+ "E054",+ () ->+ ExceptionUtils.createGhostscriptCompressionException(+ "Page drawing error"));++ @Test+ void everyCodeAKindClaimsIsCarriedBySomeException() {+ Set<String> emitted = codesEmittedByGenericInvocation();+ SELECTED_BY_CONTENT.forEach(+ (code, factory) -> {+ Throwable thrown = factory.get();+ assertThat(thrown)+ .as("the content-selected factory for %s", code)+ .isInstanceOf(ErrorCodeProvider.class);+ emitted.add(((ErrorCodeProvider) thrown).getErrorCode());+ });++ List<String> unreachable = new ArrayList<>();+ for (FailureKind kind : FailureKind.values()) {+ for (String code : kind.getErrorCodes()) {+ if (!emitted.contains(code)) {+ unreachable.add(+ kind.getId() + " claims " + code + " (" + constantFor(code) + ")");+ }+ }+ }+ assertThat(unreachable)+ .as(+ "codes no ExceptionUtils factory emits as an ErrorCodeProvider; give the"+ + " factory a coded type, or stop claiming the code")+ .isEmpty();+ }++ /**+ * Every public static {@code create*} factory, called with type defaults. One this cannot call+ * is skipped: it proves nothing, and a code only it emits fails the assertion above.+ */+ private static Set<String> codesEmittedByGenericInvocation() {+ Set<String> emitted = new HashSet<>();+ for (Method method : ExceptionUtils.class.getMethods()) {+ if (!Modifier.isStatic(method.getModifiers())+ || !method.getName().startsWith("create")+ || !Throwable.class.isAssignableFrom(method.getReturnType())) {+ continue;+ }+ Object[] args = defaultsFor(method.getParameterTypes());+ if (args == null) {+ continue;+ }+ try {+ if (method.invoke(null, args) instanceof ErrorCodeProvider provider) {+ emitted.add(provider.getErrorCode());+ }+ } catch (ReflectiveOperationException | RuntimeException notInvokable) {+ // Left out on purpose; see the method comment.+ }+ }+ return emitted;+ }++ private static Object[] defaultsFor(Class<?>[] types) {+ Object[] args = new Object[types.length];+ for (int i = 0; i < types.length; i++) {+ args[i] = defaultFor(types[i]);+ if (args[i] == null) {+ return null;+ }+ }+ return args;+ }++ private static Object defaultFor(Class<?> type) {+ if (type == String.class) return "x";+ if (type == int.class || type == Integer.class) return 1;+ if (type == long.class || type == Long.class) return 1L;+ if (type == double.class || type == Double.class) return 1.0;+ if (type == boolean.class || type == Boolean.class) return false;+ if (type == Object[].class) return new Object[0];+ if (type == List.class || type == Collection.class) return List.of();+ if (Throwable.class.isAssignableFrom(type)) return throwableOf(type);+ return null;+ }++ private static Throwable throwableOf(Class<?> type) {+ try {+ return (Throwable) type.getConstructor(String.class).newInstance("x");+ } catch (ReflectiveOperationException noStringConstructor) {+ try {+ return (Throwable) type.getConstructor().newInstance();+ } catch (ReflectiveOperationException none) {+ return null;+ }+ }+ }++ private static String constantFor(String code) {+ return Arrays.stream(ErrorCode.values())+ .filter(constant -> constant.getCode().equals(code))+ .map(Enum::name)+ .findFirst()+ .orElse("no ErrorCode constant");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.javaindex f1352d328d..2c48f1724c 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java@@ -349,12 +349,56 @@ class FailureKindTest {}@Test- void aCodeARetryCouldClearIsLeftToUnknown() {- // E051 is the bucket analyzeGhostscriptOutput falls back to for output it cannot- // recognise, so it also carries killed processes and full disks; E053 is an outright- // interruption. Claiming either would tell an owner a rerunnable failure is permanent.- assertThat(FailureKind.byErrorCode("E051")).isEmpty();- assertThat(FailureKind.byErrorCode("E053")).isEmpty();+ void aCodeARetryCouldClearSaysSoRatherThanPermanent() {+ // E053 is an outright interruption, and E051 is the bucket unrecognised Ghostscript+ // output falls into, so both are rerunnable. Their kinds lead with the retry.+ assertThat(FailureKind.byErrorCode("E053"))+ .hasValueSatisfying(+ kind ->+ assertThat(kind.getRemedy())+ .isEqualTo(FailureRemedy.TRANSIENT));+ assertThat(FailureKind.byErrorCode("E051"))+ .hasValueSatisfying(+ kind ->+ assertThat(kind.getActions())+ .first()+ .isEqualTo(FailureActionId.OPEN_IN_TOOL));+ }++ /**+ * Codes no kind claims, each with the reason. Anything else the enum names must be claimed:+ * a coded failure nobody claims lands in the bell as unrecognised.+ */+ private static final Map<String, String> UNCLAIMED_ON_PURPOSE =+ Map.of(+ "E031",+ "the catch-all a step throws with nothing more specific to say;"+ + " UNKNOWN describes it accurately",+ "E071",+ "a null argument is a programming error, not something an owner or"+ + " reviewer can act on",+ "E080",+ "MD5 unavailable is swallowed by its one caller for a fallback hash,"+ + " so it never reaches a run");++ @Test+ void everyErrorCodeIsClaimedOrLeftUnclaimedForAStatedReason() {+ Set<String> claimed =+ Stream.of(FailureKind.values())+ .flatMap(kind -> kind.getErrorCodes().stream())+ .collect(Collectors.toSet());+ List<String> unaccounted =+ Arrays.stream(ExceptionUtils.ErrorCode.values())+ .filter(code -> !claimed.contains(code.getCode()))+ .filter(code -> !UNCLAIMED_ON_PURPOSE.containsKey(code.getCode()))+ .map(code -> code.getCode() + " (" + code.name() + ")")+ .toList();+ assertThat(unaccounted)+ .as("codes no kind claims; claim them, or list them with a reason")+ .isEmpty();+ assertThat(UNCLAIMED_ON_PURPOSE.keySet())+ .as("a reason for a code some kind now claims is stale")+ .doesNotContainAnyElementsOf(claimed);}}@@ -395,8 +439,8 @@ class FailureKindTest {void aKindWithNothingToOfferDeclaresNoResolutionRatherThanAWeakOne() {// Zero resolutions is legal, so nothing else would notice one of these quietly// gaining a button. Each is here because no action the client can run would change- // the outcome: the file is the wrong type, empty, gone, or the server is missing a- // binary. A retry belongs to UNKNOWN, which says plainly that we do not know.+ // the outcome, or because the only one that might is a plain retry, which is an+ // offer rather than a fix.assertThat(Stream.of(FailureKind.values()).filter(@@ -416,6 +460,10 @@ class FailureKindTest {FailureKind.INPUT_UNAVAILABLE,FailureKind.TOOL_NOT_INSTALLED,FailureKind.STEP_CANNOT_RENDER_PAGE,+ FailureKind.STEP_TOOL_FAILED,+ FailureKind.STEP_INTERRUPTED,+ FailureKind.STEP_PAGE_TOO_LARGE,+ FailureKind.STEP_MISCONFIGURED,FailureKind.UNKNOWN);}diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 9b05e196da..b5f8967947 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -8481,6 +8481,22 @@ title = "Wrong file type"description = "A page in your file could not be drawn, so the run could not finish."title = "Page could not be rendered"+[portal.failures.kind.stepInterrupted]+description = "This step was stopped before it finished, so your file was not processed. Running it again usually works."+title = "Step was interrupted"++[portal.failures.kind.stepMisconfigured]+description = "This step's settings are not valid, so it could not run on any file. Edit the step to fix them."+title = "Step settings are invalid"++[portal.failures.kind.stepPageTooLarge]+description = "A page in your file could not be rendered at the requested resolution. Lower the DPI in the step, or split the file."+title = "Page too large to render"++[portal.failures.kind.stepToolFailed]+description = "A tool this step relies on could not process your file."+title = "Tool could not process the file"+[portal.failures.kind.toolNotInstalled]description = "This server is missing software the step needs, so the run could not start it."title = "Software not installed"diff --git a/frontend/editor/src/core/services/notificationRetry.ts b/frontend/editor/src/core/services/notificationRetry.tsindex 198390f10c..883be4d6e2 100644--- a/frontend/editor/src/core/services/notificationRetry.ts+++ b/frontend/editor/src/core/services/notificationRetry.ts@@ -54,8 +54,12 @@ export const KIND_ERROR_CODES: Record<string, readonly string[]> = {INPUT_UNREADABLE: ["E010", "E015", "E021", "E034"],INPUT_EMPTY: ["E005", "E012", "E016", "E020", "E032"],INPUT_UNAVAILABLE: ["E030", "E033"],- TOOL_NOT_INSTALLED: ["E042", "E062", "E063", "E080"],+ TOOL_NOT_INSTALLED: ["E042", "E062", "E063", "E064"],STEP_CANNOT_RENDER_PAGE: ["E054"],+ STEP_TOOL_FAILED: ["E044", "E051", "E052", "E060"],+ STEP_INTERRUPTED: ["E053"],+ STEP_PAGE_TOO_LARGE: ["E081"],+ STEP_MISCONFIGURED: ["E040", "E041", "E043", "E050", "E070", "E072"],};/** Every code any kind claims, so an unclaimed one can be recognised as belonging to UNKNOWN. */diff --git a/testing/failure-kind-codes.json b/testing/failure-kind-codes.jsonindex b2b24e6dc9..658573e935 100644--- a/testing/failure-kind-codes.json+++ b/testing/failure-kind-codes.json@@ -15,7 +15,11 @@"INPUT_UNREADABLE": ["E010", "E015", "E021", "E034"],"INPUT_EMPTY": ["E005", "E012", "E016", "E020", "E032"],"INPUT_UNAVAILABLE": ["E030", "E033"],- "TOOL_NOT_INSTALLED": ["E042", "E062", "E063", "E080"],- "STEP_CANNOT_RENDER_PAGE": ["E054"]+ "TOOL_NOT_INSTALLED": ["E042", "E062", "E063", "E064"],+ "STEP_CANNOT_RENDER_PAGE": ["E054"],+ "STEP_TOOL_FAILED": ["E044", "E051", "E052", "E060"],+ "STEP_INTERRUPTED": ["E053"],+ "STEP_PAGE_TOO_LARGE": ["E081"],+ "STEP_MISCONFIGURED": ["E040", "E041", "E043", "E050", "E070", "E072"]}}