Home >Java >javaTutorial >How to Return an HTTP 400 \'Bad Request\' Error in Spring MVC @ResponseBody Methods?
How to Handle HTTP Errors in Spring MVC @ResponseBody Methods
Problem:
When using Spring MVC with a @ResponseBody approach, how can a method respond with an HTTP 400 "bad request" error if a particular condition is not met?
Solution:
Original Approach:
The original code attempted to return a String if the condition was not met, which is not feasible since @ResponseBody expects a ResponseEntity object:
<code class="java">@ResponseBody public String match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { // TODO: how to respond with e.g. 400 "bad request"? } return json; }</code>
Solution:
Change the method's return type to ResponseEntity
<code class="java">@ResponseBody public ResponseEntity<String> match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(json, HttpStatus.OK); }</code>
For a cleaner alternative after Spring 4.1, utilize the helper methods in ResponseEntity:
<code class="java">@ResponseBody public ResponseEntity<String> match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } return ResponseEntity.ok(json); }</code>
This approach enables the return of an appropriate HTTP status code and content based on the execution result.
The above is the detailed content of How to Return an HTTP 400 \'Bad Request\' Error in Spring MVC @ResponseBody Methods?. For more information, please follow other related articles on the PHP Chinese website!