Home > Back-end >  I want to transmit a status code if the query is successful with Spring boot, how can I do it?
I want to transmit a status code if the query is successful with Spring boot, how can I do it?

Time:09-26

Although this situation is easy for ready overrided methods, I couldn't find a way for my own query.

This is my repository :

public interface CommentRepository extends JpaRepository<User , Long >{
                
     @Modifying
     @Transactional
     @Query( value="delete from users where first_name=:name" , nativeQuery=true )
     public void delete( String name );
}

This is my controller :

@RestController
@RequestMapping(path="/api/v1/users")
public class CommentController {
    
    @Autowired
    CommentRepository repository ;
    
    // Delete user
    
    @DeleteMapping(path="/delete")
    public void delete(@RequestParam String name) {
        
        repository.delete(name) ;
    }
}

For example, if I delete a user, I want to pass a status code of 200 to the developer if the query is successful.

However I want to pass different codes if the query fails.

CodePudding user response:

ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.

Have a look at Response entity using which you will be able to configure everything including status codes .

https://www.baeldung.com/spring-response-entity

CodePudding user response:

In the rest controller you can do something like:

@RestController
@RequestMapping(path="/api/v1/users")
public class CommentController {
    
    @Autowired
    CommentRepository repository ;
    
    // Delete user
    
    @DeleteMapping(path="/delete")
    public ResponseEntity<Void> delete(@RequestParam String name) {
        
        repository.delete(name);
        return ResponseEntity.ok().build();
    }
}

Since I don't know your database structure, let's say a SQLIntegrityConstraintViolationException can be thrown, you can create a service layer that will handle the exception. You will end up with something like:

@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {
  
   private final CommentRepository commentRepository;

   @Override
   public void deleteUsersByName(String name) {
     try {
         commentRepository.delete(name); //consider changing the repo method name 'delete' to be more contextual like 'deleteAllByName(String name)'
     } catch (Exception | SQLIntegrityConstraintViolationException e) //or other type, depending on your database structure
       throw new MyCustomException("my message: "   e); //create new RuntimeException with the name you prefer
   }

}

Then you have lots of ways to handle your new exception. Please read more here: https://www.baeldung.com/exception-handling-for-rest-with-spring

One of the ways is to have this inside your @RestController class

@ExceptionHandler({MyCustomException.class})
    public ResponseEntity<Void> handleConstrainViolationException() {
        return ResponseEntity.internalServerError(); //just an example
    }

for the last part you can play around with the exceptions thrown on the service layer and return appropriate status code from the corresponding exception handler. Consider having a global exception handler as stated into the article on Baeldung above. Hope it helps a little bit.

  • Related