Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3667

Spring Boot (3.5.0) - Rest Controller - 400 with HTML response body

$
0
0

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

  1. adding exception handler for 'NoHandlerFoundException' at @ControllerAdvice class
  2. added throw-exception-in-no-handler-found in the application config
  3. Extended ErrorController with request mapping "/error"
  4. implements RequestRejectedHandlerNo 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")@Validatedpublic 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


Viewing all articles
Browse latest Browse all 3667

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>