I am encountering a problem that spring boot restful service returns 400(badRequest) with html response body when the request uri path variable is blank for example:
URI path: ../v1/users/{id}/job where id is blank and so the request path will be ../v1/users//job
.
I tried following options
- adding exception handler for ‘NoHandlerFoundException’ at @ControllerAdvice class
- added throw-exception-in-no-handler-found in the application config
- Extended ErrorController with request mapping “/error”
- implements RequestRejectedHandler
No luck.
How to deal with this kind of an exception to write custom json in the response.
Sample Code:
import jakarta.validation.constraints.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/v1")
@Validated
public class SampleController {@GetMapping(value =
"/users/{id}/jobs")
public ResponseEntity<?> update(
@RequestHeader(value = "requestId") String requestId,
@PathVariable("id") @NotNull String userId) {
String formattedMessage = "GET jobs [%s
%s]".formatted(requestId,userId);
System.out.print(formattedMessage);
return ResponseEntity.noContent().build();
}
}
REQUEST:
curl http://localhost:8080/v1/users//jobs -H ‘requestId: b4c0-a6ddc4807cf1’
RESPONSE:
<!doctype html>HTTP Status 400 – Bad Requestbody {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}
HTTP Status 400 – Bad Request
5