Files
Vaessl/backend/src/main/java/com/vaessl/app/exception/GlobalExceptionHandler.java
T

73 lines
3.1 KiB
Java

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(WrongServiceTypeException.class)
public ProblemDetail handleWrongServiceType(WrongServiceTypeException e) {
return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(),
WRONG_SERVICE_TYPE.getMessage());
}
@ExceptionHandler(EmptyCredentialsException.class)
public ProblemDetail handleEmptyCredentials(EmptyCredentialsException e) {
return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(),
BAD_REQUEST_EMPTY_FIELDS.getMessage() + " " + e.getMissingFields());
}
@ExceptionHandler(ConnectionNotFoundException.class)
public ProblemDetail handleConnectionNotFound(ConnectionNotFoundException e) {
return ProblemDetail.forStatusAndDetail(CONNECTION_NOT_FOUND.getStatus(), CONNECTION_NOT_FOUND.getMessage());
}
@ExceptionHandler(RemoteApiException.class)
public ProblemDetail handleRemoteApiException(RemoteApiException e) {
return ProblemDetail.forStatusAndDetail(REMOTE_API_EMPTY_RESPONSE.getStatus(),
REMOTE_API_EMPTY_RESPONSE.getMessage() + e.getAppUrl());
}
}