Best practice to send response in spring boot

前端 未结 2 1768
执念已碎
执念已碎 2021-01-01 04:46

I\'m coding REST Api-s in spring boot. I want to make sure that my code is readable to front-end developers using swagger API development tool (Swagger). For example

2条回答
  •  旧巷少年郎
    2021-01-01 05:24

    I would recommend to do it like this .

    @GetMapping("/getOne")
    public Response getOne(@RequestParam String id) {
            ResponseEntity resbranch;
            ResponseEntity reserror;
            try {
                resbranch=new ResponseEntity(branchService.getOne(id), HttpStatus.OK);
                return Response.status(200).entity(resbranch).build();
    
            } catch (Exception e) {
                reserror=new ResponseEntity(new FindError(e.getMessage()), HttpStatus.BAD_REQUEST);
                return Response.status(400).entity(reserror).build();
            }
        }
    

    200 is for OK and 400 is for bad request. Here there wont be anymore ambiguous types..

提交回复
热议问题