4

Spring5 has introduced ResponseStatusException, which has put me in a dilemma as to in what scenario I can use a ResponseStatusException and ControllerAdvice as both of them are quiet similar.

Can anyone help me with this. Thanks in advance.

Sonali
  • 73
  • 1
  • 6

2 Answers2

7

Lets first understand what is ResponseStatusException and ControllerAdvice

ResponseStatusException is a programmatic alternative to @ResponseStatus and is the base class for exceptions used for applying a status code to an HTTP response.

@GetMapping("/actor/{id}")
public String getActorName(@PathVariable("id") int id) {
    try {
        return actorService.getActor(id);
    } catch (ActorNotFoundException ex) {
        throw new ResponseStatusException(
          HttpStatus.NOT_FOUND, "Actor Not Found", ex);
    }
}

The @ControllerAdvice annotation allows us to consolidate multiple, scattered @ExceptionHandlers into a single, global error handling component.

@ControllerAdvice
public class RestResponseEntityExceptionHandler 
  extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value 
      = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        return ResponseEntity<Object>;
    }
}

Coming back to your questions of when to use what:

  1. If you want to provide a unified and global way of exception handling make use of ControllerAdvice. It also eliminates code duplication which might be caused by ResponseStatusException.
  2. In order to throw different error code and responses for the same exception, don't want to create custom exception classes and to avoid tight coupling make use of ResponseStatusException.

References:

  1. Spring ResponseStatusException

  2. Error Handling for REST with Spring

1

Overall it is better to use @ControllerAdvice if you are looking for a more unified solution but ResponseStatusException is also handy too in case you don't want to make different Exception classes and want to keep it simple.

for examples and more info you can refer to the following articles: