Luk
Luk

Reputation: 1159

Does spring boot automatically take care of error handling in the context of JpaRepository methods?

When using Spring Boot, I am unsure if error handling is already being taken care of by the Spring Framework, or if I have to implement it. For example, consider a controller method, which handles a DELETE request:

@DeleteMapping("/{studentId}")
public ResponseEntity<Long> deleteProfilePicture(@PathVariable Long studentId) {
  return  ResponseEntity.ok(profilePictureService.deleteprofilePictureByStudentId(studentId));
}

Is this fine, or should I instead wrap it inside a try-catch block:

@DeleteMapping("/{studentId}")
public ResponseEntity<Long> deleteProfilePicture(@PathVariable Long studentId) throws Exception {
    try {
        profilePictureService.deleteProfilePictureByStudentId(studentId));
    } catch (DataAccessException e) {
        throw new Exception("cannot delete profile picture of student: " + studentId);
    }
}

Also: If I let my method deleteProfilePicture throw this Exception, who is handling the Exception? This must somehow be taken care of by Spring Boot, since it is possible to implement it without yielding any errors. Anyhow, what is the correct way of error handling in this scenario?

Upvotes: 1

Views: 599

Answers (1)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17500

Spring Boot will turn the exception into an error response to the caller of the REST API. This does not mean that you shouldn't implement your own error handling logic, which you definitely should. As an example, you could use @ControllerAdvice to have a global exception handling for your application. Something along the following lines:

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Object> handleGenericExceptions(Exception exception, WebRequest webRequest) {
        log.error("Handling: ", exception);

        HttpStatus errorCode = HttpStatus.INTERNAL_SERVER_ERROR;

        return this.handleExceptionInternal(exception, new ErrorInfo(errorCode.value(), "Unexpected Internal Server Error"), new HttpHeaders(), errorCode, webRequest);
    }

}

You can read more about error handling in Spring Boot at https://www.baeldung.com/exception-handling-for-rest-with-spring.

Upvotes: 2

Related Questions