@RestControllerAdvice
public class TratadorDeErrores {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity tratarError404() {
return ResponseEntity.notFound().build();
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity tratarError400(MethodArgumentNotValidException e) {
var errores = e.getFieldErrors().stream()
.map(DatosErrorValidacion::new)
.toList();
return ResponseEntity.badRequest().body(errores);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity tratarError400Json(HttpMessageNotReadableException e) {
return ResponseEntity.badRequest().body("El cuerpo de la solicitud es inválido.");
}
@ExceptionHandler(Exception.class)
public ResponseEntity tratarError500(Exception e) {
return ResponseEntity.internalServerError().body("Ocurrió un error interno en el servidor.");
}
}
public record DatosErrorValidacion(
String campo,
String error
) {
public DatosErrorValidacion(FieldError error) {
this(error.getField(), error.getDefaultMessage());
}
}
@PostMapping
@Transactional
public ResponseEntity registrar(@RequestBody @Valid DatosRegistroPaciente datos,
UriComponentsBuilder uriBuilder) {
var paciente = new Paciente(datos);
repository.save(paciente);
var uri = uriBuilder.path("/pacientes/{id}").buildAndExpand(paciente.getId()).toUri();
return ResponseEntity.created(uri).body(new DatosDetallePaciente(paciente));
}
@RestControllerAdvice
public class TratadorDeErrores {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity tratarError404() {
return ResponseEntity.notFound().build();
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity tratarError400(MethodArgumentNotValidException e) {
var errores = e.getFieldErrors().stream()
.map(DatosErrorValidacion::new)
.toList();
return ResponseEntity.badRequest().body(errores);
}
}