Files
mealprep/backend/src/main/java/com/recipeapp/common/GlobalExceptionHandler.java
2026-04-04 18:18:27 +02:00

47 lines
1.9 KiB
Java

package com.recipeapp.common;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex) {
List<String> details = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.toList();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiError.of("VALIDATION_ERROR", "Validation failed", details));
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiError> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiError.of("NOT_FOUND", ex.getMessage()));
}
@ExceptionHandler(ConflictException.class)
public ResponseEntity<ApiError> handleConflict(ConflictException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body(ApiError.of("CONFLICT", ex.getMessage()));
}
@ExceptionHandler(ForbiddenException.class)
public ResponseEntity<ApiError> handleForbidden(ForbiddenException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiError.of("FORBIDDEN", ex.getMessage()));
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ApiError> handleBusinessValidation(ValidationException ex) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
.body(ApiError.of("VALIDATION_ERROR", ex.getMessage()));
}
}