Friday, August 5, 2022

[FIXED] When to use ResponseStatusException and ControllerAdvice

Issue

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.


Solution

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



Answered By - Anjan Krishna
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.