| 1 | package com.tecmilenio.mapsconect.exception; |
| 2 | |
| 3 | import com.tecmilenio.mapsconect.dto.ApiResponse; |
| 4 | import org.springframework.http.HttpStatus; |
| 5 | import org.springframework.http.ResponseEntity; |
| 6 | import org.springframework.security.access.AccessDeniedException; |
| 7 | import org.springframework.validation.FieldError; |
| 8 | import org.springframework.web.bind.MethodArgumentNotValidException; |
| 9 | import org.springframework.web.bind.annotation.ExceptionHandler; |
| 10 | import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 11 | |
| 12 | import java.util.HashMap; |
| 13 | import java.util.Map; |
| 14 | |
| 15 | @RestControllerAdvice |
| 16 | public class GlobalExceptionHandler { |
| 17 | |
| 18 | @ExceptionHandler(ResourceNotFoundException.class) |
| 19 | public ResponseEntity<ApiResponse<?>> handleResourceNotFound(ResourceNotFoundException ex) { |
| 20 | return ResponseEntity.status(HttpStatus.NOT_FOUND) |
| 21 | .body(ApiResponse.error(404, ex.getMessage())); |
| 22 | } |
| 23 | |
| 24 | @ExceptionHandler(AccessDeniedException.class) |
| 25 | public ResponseEntity<ApiResponse<?>> handleAccessDenied(AccessDeniedException ex) { |
| 26 | return ResponseEntity.status(HttpStatus.FORBIDDEN) |
| 27 | .body(ApiResponse.error(403, "Acceso denegado")); |
| 28 | } |
| 29 | |
| 30 | @ExceptionHandler(MethodArgumentNotValidException.class) |
| 31 | public ResponseEntity<ApiResponse<?>> handleValidationExceptions(MethodArgumentNotValidException ex) { |
| 32 | Map<String, String> errors = new HashMap<>(); |
| 33 | ex.getBindingResult().getAllErrors().forEach(error -> { |
| 34 | String fieldName = ((FieldError) error).getField(); |
| 35 | String errorMessage = error.getDefaultMessage(); |
| 36 | errors.put(fieldName, errorMessage); |
| 37 | }); |
| 38 | return ResponseEntity.status(HttpStatus.BAD_REQUEST) |
| 39 | .body(ApiResponse.error(400, errors.toString())); |
| 40 | } |
| 41 | |
| 42 | @ExceptionHandler(Exception.class) |
| 43 | public ResponseEntity<ApiResponse<?>> handleGenericException(Exception ex) { |
| 44 | return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) |
| 45 | .body(ApiResponse.error(500, "Error interno del servidor")); |
| 46 | } |
| 47 | |
| 48 | } |