package com.vaessl.app.exception; import org.springframework.http.ProblemDetail; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.ResourceAccessException; import static com.vaessl.app.exception.ErrorMessage.*; import java.util.stream.Collectors; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ProblemDetail handleEmptyCredentialInput(MethodArgumentNotValidException e) { String defaultMessages = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage) .collect(Collectors.joining(", ")); return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(), BAD_REQUEST_EMPTY_FIELDS.getMessage() + " [" + defaultMessages + "]"); } @ExceptionHandler(HttpClientErrorException.Unauthorized.class) public ProblemDetail handleUnauthorizedAccess(HttpClientErrorException e) { return ProblemDetail.forStatusAndDetail(UNAUTHORIZED_WRONG_LOGIN.getStatus(), UNAUTHORIZED_WRONG_LOGIN.getMessage()); } @ExceptionHandler(ResourceAccessException.class) public ProblemDetail handleNoConnection(ResourceAccessException e) { return ProblemDetail.forStatusAndDetail(SERVICE_UNAVAILABLE_UNREACHABLE_URL.getStatus(), SERVICE_UNAVAILABLE_UNREACHABLE_URL.getMessage()); } @ExceptionHandler(HttpServerErrorException.class) public ProblemDetail handleTimeoutOrNotFound(HttpServerErrorException e) { return ProblemDetail .forStatusAndDetail(e.getStatusCode(), SERVER_ERROR_GENERAL.getMessage() + e.getStatusText()); } @ExceptionHandler(EmptyCredentialsException.class) public ProblemDetail handleEmptyCredentials(EmptyCredentialsException e) { return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(), BAD_REQUEST_EMPTY_FIELDS.getMessage() + " " + e.getMissingFields()); } }