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

后端 未结 12 1494
南旧
南旧 2020-12-07 09:15

I have written simple rest application using Spring MVC 4 (or Spring-Boot). Within the controller I have return ResponseEntity. But in some cases I want to give

相关标签:
12条回答
  • 2020-12-07 09:24

    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.

    0 讨论(0)
  • 2020-12-07 09:25

    Here is a way that I would do it:

    public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.
    
     try {
      Integer.parseInt(player);
      return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
     } catch (Exception e) {
    
    
     }
     Message msg = new Message(player, "Hello " + player);
     return new ResponseEntity < Message > (msg, HttpStatus.OK);
    
    }
    
    @RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.
    
     try {
      Integer.parseInt(player);
      List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
      errs.add(new ErrorResponse("111", "player is not found"));
      return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
     } catch (Exception e) {
    
    
     }
     Message msg = new Message(player, "Hello " + player);
     List < Message > msgList = new ArrayList < Message > ();
     msgList.add(msg);
     return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);
    
    }
    
    0 讨论(0)
  • 2020-12-07 09:25

    For exceptional cases, I will recommend you to adopt RFC-7807 Problem Details for HTTP APIs standard in your application.

    Zalando's Problems for Spring provides a good integration with Spring Boot, you can integrate it easily with your existing Spring Boot based application. Just like what JHipster did.

    After adopting RFC-7087 in your application, just throw Exception in your controller method, and you will get a detailed and standard error response like:

       {
        "type": "https://example.com/probs/validation-error",
        "title": "Request parameter is malformed.",
        "status": 400
        "detail": "Validation error, value of xxx should be a positive number.",
        "instance": "/account/12345/msgs/abc",
       }
    
    0 讨论(0)
  • 2020-12-07 09:28

    i am not sure but, I think you can use @ResponseEntity and @ResponseBody and send 2 different one is Success and second is error message like :

    @RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
    @ResponseBody
    Book bookInfo2() {
        Book book = new Book();
        book.setBookName("Ramcharitmanas");
        book.setWriter("TulasiDas");
        return book;
    }
    
    @RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
    public ResponseEntity<Book> bookInfo3() {
        Book book = new Book();
        book.setBookName("Ramayan");
        book.setWriter("Valmiki");
        return ResponseEntity.accepted().body(book);
    }
    

    For more detail refer to this: http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

    0 讨论(0)
  • 2020-12-07 09:31

    You can also implement like this to return Success and Error on a same request mapping method,use Object class(Parent class of every class in java) :-

    public ResponseEntity< Object> method() {                                                                                                                                                                                                                                                                                                                                                                                  
        boolean b = //  logic  here   
          if (b)  
            return new ResponseEntity< Object>(HttpStatus.OK);      
        else      
            return new ResponseEntity< Object>(HttpStatus.CONFLICT); //appropriate error code   
    }
    
    0 讨论(0)
  • 2020-12-07 09:32

    Its possible to return ResponseEntity without using generics, such as follows,

    public ResponseEntity method() {
        boolean isValid = // some logic
        if (isValid){
            return new ResponseEntity(new Success(), HttpStatus.OK);
        }
        else{
            return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);
        }
    }
    
    0 讨论(0)
提交回复
热议问题