package se.bilhalsning.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 se.bilhalsning.dto.ErrorResponse; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(InvalidCredentialsException.class) public ResponseEntity handleInvalidCredentials(InvalidCredentialsException ex) { return ResponseEntity .status(HttpStatus.UNAUTHORIZED) .body(new ErrorResponse(ex.getMessage())); } @ExceptionHandler(EmailAlreadyExistsException.class) public ResponseEntity handleEmailAlreadyExists(EmailAlreadyExistsException ex) { return ResponseEntity .status(HttpStatus.CONFLICT) .body(new ErrorResponse("E-postadressen är redan registrerad")); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity handleValidation(MethodArgumentNotValidException ex) { String message = ex.getBindingResult().getFieldErrors().stream() .map(e -> e.getField() + ": " + e.getDefaultMessage()) .reduce((a, b) -> a + ", " + b) .orElse("Ogiltig indata"); return ResponseEntity .badRequest() .body(new ErrorResponse(message)); } @ExceptionHandler(Exception.class) public ResponseEntity handleGeneral(Exception ex) { log.error("Unhandled exception", ex); return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new ErrorResponse("Ett internt fel uppstod")); } }