Home >Java >javaTutorial >How to Return an HTTP 400 \'Bad Request\' Error in Spring MVC @ResponseBody Methods?

How to Return an HTTP 400 \'Bad Request\' Error in Spring MVC @ResponseBody Methods?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 02:02:02210browse

How to Return an HTTP 400

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, where T is the expected response type. This allows you to leverage the HttpStatus enumeration to specify the HTTP status code:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn