Handle Embedded Tomcat Exception in Spring Boot Handle Embedded Tomcat Exception in Spring Boot spring spring

Handle Embedded Tomcat Exception in Spring Boot


This is a feature of Tomcat itself as mentioned in this answer.

However, you can do something like this by allowing the special characters that you are expecting as part of your request and handle them yourself.

First, you need to allow the special characters that you would need to handle by setting up the relaxedQueryChars like this.

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;import org.springframework.boot.web.server.WebServerFactoryCustomizer;import org.springframework.stereotype.Component;@Componentpublic class TomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {@Overridepublic void customize(TomcatServletWebServerFactory factory) {    factory.addConnectorCustomizers((connector) -> {        connector.setAttribute("relaxedQueryChars", "^");    }); }}

and later handle the special characters in each of your requests or create an interceptor and handle it in a common place.

To handle it in the request individually you can do something like this.

import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class DemoRestController {@GetMapping(value = "/working")public void working() {    throw new java.lang.IllegalArgumentException();}@GetMapping(value = "/not-working")public String notWorking(@RequestParam String demo) {    if (demo.contains("^")) {        throw new java.lang.IllegalArgumentException("^");    }    return "You need to pass e.g. the character ^ as a request param to test this.";}}

You might also want to refer this answer to decide if you really need this fix.