Skip to content

Commit

Permalink
fix: update correct 404 responses handling
Browse files Browse the repository at this point in the history
  • Loading branch information
thisdudkin committed Aug 10, 2024
1 parent 9fce1ec commit 38178d9
Showing 1 changed file with 20 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

package org.springframework.samples.petclinic.rest.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -62,7 +60,7 @@ public ErrorInfo(Exception ex) {
/**
* Handles all general exceptions by returning a 500 Internal Server Error status with error details.
*
* @param e The exception to be handled
* @param e The exception to be handled
* @return A {@link ResponseEntity} containing the error information and a 500 Internal Server Error status
*/
@ExceptionHandler(Exception.class)
Expand Down Expand Up @@ -107,4 +105,23 @@ public ResponseEntity<ErrorInfo> handleDataIntegrityViolationException(DataInteg
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorInfo);
}

/**
* Handles exception thrown by Bean Validation on controller methods parameters
*
* @param ex The thrown exception
* @return an empty response entity
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(BAD_REQUEST)
@ResponseBody
public ResponseEntity<ErrorInfo> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
BindingErrorsResponse errors = new BindingErrorsResponse();
BindingResult bindingResult = ex.getBindingResult();
if (bindingResult.hasErrors()) {
errors.addAllErrors(bindingResult);
return ResponseEntity.badRequest().body(new ErrorInfo("MethodArgumentNotValidException", "Validation failed"));
}
return ResponseEntity.badRequest().build();
}

}

0 comments on commit 38178d9

Please sign in to comment.