What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

We Are Going To Discuss About What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot. So lets Start this Java Article.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

  1. What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

    Your controller method should only return ResponseEntity<Success>. It will not be responsible for returning error or exception responses.

  2. best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

    Your controller method should only return ResponseEntity<Success>. It will not be responsible for returning error or exception responses.

Solution 1

I recommend using Spring’s @ControllerAdvice to handle errors. Read this guide for a good introduction, starting at the section named “Spring Boot Error Handling”. For an in-depth discussion, there’s an article in the Spring.io blog that was updated on April, 2018.

A brief summary on how this works:

  • Your controller method should only return ResponseEntity<Success>. It will not be responsible for returning error or exception responses.
  • You will implement a class that handles exceptions for all controllers. This class will be annotated with @ControllerAdvice
  • This controller advice class will contain methods annotated with @ExceptionHandler
  • Each exception handler method will be configured to handle one or more exception types. These methods are where you specify the response type for errors
  • For your example, you would declare (in the controller advice class) an exception handler method for the validation error. The return type would be ResponseEntity<Error>

With this approach, you only need to implement your controller exception handling in one place for all endpoints in your API. It also makes it easy for your API to have a uniform exception response structure across all endpoints. This simplifies exception handling for your clients.

Original Author Mark Norman Of This Content

Solution 2

You can return generic wildcard <?> to return Success and Error on a same request mapping method

public ResponseEntity<?> method() {
    boolean b = // some logic
    if (b)
        return new ResponseEntity<Success>(HttpStatus.OK);
    else
        return new ResponseEntity<Error>(HttpStatus.CONFLICT); //appropriate error code
}

@Mark Norman answer is the correct approach

Original Author Saravana Of This Content

Solution 3

Spring 2 introduced ResponseStatusException using this you can return String, different HTTP status code, DTO at the same time.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Original Author Sathia Of This Content

Solution 4

Using custom exception class you can return different HTTP status code and dto objects.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Exception class

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

Original Author Sathia Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment