package com.lincfusion.udyamlinc.common; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.stream.Collectors; /** Every failure leaves the service in the same envelope the UI already parses. */ @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity> notFound(ResourceNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.fail(e.getMessage())); } @ExceptionHandler(BadCredentialsException.class) public ResponseEntity> badCredentials(BadCredentialsException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.fail(e.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity> invalid(MethodArgumentNotValidException e) { String detail = e.getBindingResult().getFieldErrors().stream() .map(f -> f.getField() + " " + f.getDefaultMessage()) .collect(Collectors.joining("; ")); return ResponseEntity.badRequest().body(ApiResponse.fail(detail)); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity> illegal(IllegalArgumentException e) { return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage())); } @ExceptionHandler(Exception.class) public ResponseEntity> unexpected(Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ApiResponse.fail("Unexpected error: " + e.getMessage())); } }