rasilvap
rasilvap

Reputation: 2149

Return response messages in spring boot

I am working with spring boot with a h2 database. I would like to return a 201 message when the register is inserted succesfully and a 400 when is duplicated. I am using ResponseEntity to achieve this, fot example , the next is my create method from the Service:

    @Override
    public ResponseEntity<Object> createEvent(EventDTO eventDTO) {
        if (eventRepository.findOne(eventDTO.getId()) != null) {
            //THis is a test, I am looking for the correct message
            return new ResponseEntity(HttpStatus.IM_USED);
        }
        Actor actor = actorService.createActor(eventDTO.getActor());
        Repo repo = repoService.createRepo(eventDTO.getRepo());
        Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
        eventRepository.save(event);
        return new ResponseEntity(HttpStatus.CREATED);
    }

This is my controller:

    @PostMapping(value = "/events")
    public ResponseEntity addEvent(@RequestBody EventDTO body) {
        return eventService.createEvent(body);
    }

But I'm not getting any message in the browser, I am doing different tests with postman and when I consult for all the events, the result is correct, but each time that I make a post I dont get any message in the browser, I am not pretty sure what is the cause of this issue. Any ideas?

Upvotes: 0

Views: 10918

Answers (2)

Romil Patel
Romil Patel

Reputation: 13727

The ideal way to send Response to the client is to create DTO/DAO with ResponseEntity in Controller

Controller.java

@PostMapping("/test")
        public ResponseEntity<Object> testApi(@RequestBody User user)
        {
            System.out.println("User: "+user.toString());
            return assetService.testApi(user);
        }

Service.java

public ResponseEntity testApi(User user) {  
        if(user.getId()==1)
            return new ResponseEntity("Created",HttpStatus.CREATED);
        else
            return new ResponseEntity("Used",HttpStatus.IM_USED);   
           // for BAD_REQUEST(400) return new ResponseEntity("Bad Request",HttpStatus.BAD_REQUEST);
    }

Tested using Postman

Status 201 Created Created

Status 226 IM Used Status IMUSED

Upvotes: 1

Avi
Avi

Reputation: 1528

Okay, I really don't feel good that service sending the ResponseEntity but not Controller.You could use @ResponseStatus and ExceptionHandler classes for these cases, like below.

Create a class in exception package

GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(DataIntegrityViolationException.class) // NOTE : You could create a custom exception class to handle duplications
    public void handleConflict() {
    }
}

Controller.java

@PostMapping(value = "/events")
@ResponseStatus(HttpStatus.CREATED) // You don't have to return any object this will take care of the status
public void addEvent(@RequestBody EventDTO body) {
   eventService.createEvent(body);
}

Now changing the service would look like,

Service.java

@Override
public void createEvent(EventDTO eventDTO) { // No need to return
   if (eventRepository.findOne(eventDTO.getId()) != null) {
        throw new DataIntegrityViolationException("Already exists"); // you have to throw the same exception which you have marked in Handler class
   }
   Actor actor = actorService.createActor(eventDTO.getActor());
   Repo repo = repoService.createRepo(eventDTO.getRepo());
   Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
   eventRepository.save(event);
}

Upvotes: 0

Related Questions