What type should I call ResponseEntity with?

Viewed 1014

I have a controller

@RestController
public class BookController {
    @GetMapping("/find-by-name/{name}")
    public ResponseEntity<BookEntity> findByName(@PathVariable String name) {
      ...

if the name is found, then in this method I return

return  ResponseEntity.ok(book);

if not, then

return new ResponseEntity("name= " + name + " not found", HttpStatus.NOT_ACCEPTABLE);

Everything works, but the compiler swears:

Raw use of parameterized class 'ResponseEntity' 
Unchecked assignment: 'org.springframework.http.ResponseEntity' to 'org.springframework.http.ResponseEntity<BookEntity>' 
Unchecked call to 'ResponseEntity(T, HttpStatus)' as a member of raw type 'org.springframework.http.ResponseEntity' 

I tried to do this (I found this option on the website spring.io)

public ResponseEntity<?> findByName(@PathVariable String name) {
...
return new ResponseEntity<>("name= " + name + " not found", HttpStatus.NOT_ACCEPTABLE);

That error is gone, but now swears on this line:

Generic wildcard types should not be used in return types

The code works in both versions, but I would like to understand how to implement it correctly.

2 Answers

You could use Object as Class in your diamond operator:

public ResponseEntity<Object> someMethod() {
  return new ResponseEntity<>("Some Object", HttpStatus.OK);
}

This works fine for me so far. This works because everything extends from Object.

For Error Handling I would use the RestControllerAdvice. The Method below is called, when an IllegalArgumentException reaches to the Controller method.

@RestControllerAdvice
public class RestControllerErrorHandler {

  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(IllegalArgumentException.class)
  public ResponseEntity<String> handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException e) {
    return new ResponseEntity<>("your error message", HttpStatus.BAD_REQUEST);
  }
}

For further information take a look here. This type of global exception handling is very practical when you use RuntimeExceptions in your application.

ResponseEntity represents an HTTP response, including headers, body, and status. Usually a response should contain a body, be it String, Void or any other object of your liking. Hence, ResponseEntity where T signifies the type of the body. For instance,

public ResponseEntity<ObjectType> getObjectTYpe() {
....
return new ResponseEntity<ObjectType>(response, httpstatus);
}

or you can use this form:

return ResponseEntity.accepted().body(body);
Related