{"record":{"id":"afe175eba82c3311","repo":"perwendel/spark","slug":"this-must-be-done-after-route-mapping-has-begun","errorCode":null,"errorMessage":"This must be done after route mapping has begun","messagePattern":"This must be done after route mapping has begun","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"src/main/java/spark/Service.java","lineNumber":185,"sourceCode":"    public synchronized Service port(int port) {\n        if (initialized) {\n            throwBeforeRouteMappingException();\n        }\n        this.port = port;\n        return this;\n    }\n\n    /**\n     * Retrieves the port that Spark is listening on.\n     *\n     * @return The port Spark server is listening on.\n     * @throws IllegalStateException when the server is not started\n     */\n    public synchronized int port() {\n        if (initialized) {\n            return port;\n        } else {\n            throw new IllegalStateException(\"This must be done after route mapping has begun\");\n        }\n    }\n\n    /**\n     * Set the connection to be secure, using the specified keystore and\n     * truststore. This has to be called before any route mapping is done. You\n     * have to supply a keystore file, truststore file is optional (keystore\n     * will be reused). By default, client certificates are not checked.\n     * This method is only relevant when using embedded Jetty servers. It should\n     * not be used if you are using Servlets, where you will need to secure the\n     * connection in the servlet container\n     *\n     * @param keystoreFile       The keystore file location as string\n     * @param keystorePassword   the password for the keystore\n     * @param truststoreFile     the truststore file location as string, leave null to reuse\n     *                           keystore\n     * @param truststorePassword the trust store password\n     * @return the object with connection set to be secure","sourceCodeStart":167,"sourceCodeEnd":203,"githubUrl":"https://github.com/perwendel/spark/blob/1973e402f5d4c1442ad34a1d38ed0758079f7773/src/main/java/spark/Service.java#L167-L203","documentation":"Service.port() returns the port the embedded Spark server is actually listening on. That value only exists once route mapping has begun and the server configuration has been initialized; before that the port field is meaningless. Spark therefore throws IllegalStateException if port() is called too early, as documented by its @throws clause.","triggerScenarios":"Calling port() on the Service instance (or the static Spark.port()) before any route mapping call (get/post/staticFiles etc.) has triggered initialization — e.g. calling it immediately at the top of main() before mapping routes.","commonSituations":"Logging 'running on port X' before routes are mapped; reading the port in a constructor or static initializer; frameworks/integration code that query the port at startup before defining routes.","solutions":["Move the port() call after route mapping has begun (after at least one get/post/put/etc. or staticFiles call), ideally after init() and awaitInitialization().","If you need the port before mapping, set it explicitly with port(4567) and use your own constant instead of reading it back.","Use awaitInitialization() first, then call port() to ensure the server is fully started."],"exampleFix":"// before\nSpark.get(\"/hello\", (req, res) -> \"hi\");\nint p = Spark.port(); // may throw if called before mapping\n// after\nSpark.get(\"/hello\", (req, res) -> \"hi\");\nSpark.awaitInitialization();\nint p = Spark.port(); // safe","handlingStrategy":"try-catch","validationCode":"if (sparkService != null && isRouteMappingStarted()) {\n    int p = sparkService.port();\n}","typeGuard":"boolean portReadable(spark.Service s) { return s != null && isRouteMappingStarted(); } // no public initialized check; track mapping start yourself","tryCatchPattern":"try {\n    int p = Spark.port();\n} catch (IllegalStateException e) {\n    // called before route mapping; use configured default instead\n    int p = DEFAULT_PORT;\n}","preventionTips":["Call port() only after awaitInitialization().","Track whether you've mapped routes before querying server state.","Store the port you set with port(int) in your own constant for early access."],"tags":["java","illegal-state","server-lifecycle"],"backgroundTag":"invalid-state-transition","analyzedSha":"1973e402f5d4c1442ad34a1d38ed0758079f7773","analyzedAt":"2026-09-10T14:38:22.866Z","contentChangedAt":"2026-09-10T14:38:22.866Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}