Spring ResponseEntity best practice

10,555

You don´t need to use a generic Pojo, using RequestMapping you can create different responses for every Http code. In this example I show how to control errors and give a response accordingly.

This is the RestController with the service specification

@RestController
public class User {

    @RequestMapping(value="/myapp/user/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> getId(@PathVariable int id){

        if(id>10)
            throw new UserNotFoundException("User not found");

        return ResponseEntity.ok("" + id);
    }

    @ExceptionHandler({UserNotFoundException.class})
    public ResponseEntity<ErrorResponse> notFound(UserNotFoundException ex){

        return new ResponseEntity<ErrorResponse>(
            new ErrorResponse(ex.getMessage(), 404, "The user was not found") , HttpStatus.NOT_FOUND);
    }
}

Within the getId method there is a little logic, if the customerId < 10 It should response the Customer Id as part of the body message but an Exception should be thrown when the customer is bigger than 10 in this case the service should response with an ErrorResponse.

public class ErrorResponse {

    private String message;
    private int code;
    private String moreInfo;

    public ErrorResponse(String message, int code, String moreInfo) {
        super();
        this.message = message;
        this.code = code;
        this.moreInfo = moreInfo;
    }

    public String getMessage() {

        return message;
    }

    public int getCode() {

        return code;
    }

    public String getMoreInfo() {

        return moreInfo;
    }
}

And finally I'm using an specific Exception for a "Not Found" error

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}
Share:
10,555
user1154644
Author by

user1154644

Updated on August 20, 2022

Comments

  • user1154644
    user1154644 over 1 year

    I am new to RESTful web services in general, and am learning the Spring implementation of web services.

    I am particularly interested in learning how to properly use ResponseEntity return types for most of my use cases.

    I have one endpoint:

    /myapp/user/{id}
    

    This endpoint supports a GET request, and will return a JSON formatted string of the User object whose ID is {id}. I plan to annotate the controller method as producing JSON.

    In the case that a user with ID {id} exists, I set a status of 200, and set the JSON string of the user in the body.

    In the event that no user exists with that ID, I was going to return some flavor of a 400 error, but I am not sure what to set in the body of the ResponseEntity. Since I annotate the endpoint method as producing JSON, should I come up with a generic POJO that represents an error, and return that as JSON?