Skip to content

Commit

Permalink
Log refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitolo-Andrea committed Oct 22, 2024
1 parent ed7f19a commit 8eabe7b
Show file tree
Hide file tree
Showing 20 changed files with 128 additions and 101 deletions.
8 changes: 4 additions & 4 deletions src/main/java/it/gov/pagopa/common/utils/Utils.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package it.gov.pagopa.common.utils;

import it.gov.pagopa.common.web.exception.EmdEncryptionException;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -9,7 +10,6 @@
@Slf4j
public class Utils {


private Utils(){}
public static String createSHA256(String fiscalCode) {
try {
Expand All @@ -25,14 +25,14 @@ public static String createSHA256(String fiscalCode) {
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
log.error("Something went wrong creating SHA256");
log.info("Something went wrong creating SHA256");
throw new EmdEncryptionException("Something went wrong creating SHA256",true,e);
}
}

public static String inputSanify(String message){
if (message != null)
return message.replaceAll("[\\r\\n]", "");
return "[EMD][WARNING] Null log";
return message.replaceAll("[\\r\\n]", " ");
return "[EMD][WARNING] Null log";
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package it.gov.pagopa.common.web.exception;


import it.gov.pagopa.common.utils.CommonConstants.ExceptionCode;
import it.gov.pagopa.common.utils.CommonConstants;

public class EmdEncryptionException extends ServiceException {

public EmdEncryptionException(String message, boolean printStackTrace, Throwable ex) {
this(ExceptionCode.GENERIC_ERROR, message, printStackTrace, ex);
this(CommonConstants.ExceptionCode.GENERIC_ERROR, message, printStackTrace, ex);
}
public EmdEncryptionException(String code, String message, boolean printStackTrace, Throwable ex) {
super(code, message,null, printStackTrace, ex);
Expand Down
20 changes: 6 additions & 14 deletions src/main/java/it/gov/pagopa/common/web/exception/ErrorManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand All @@ -23,9 +22,9 @@ public ErrorManager(@Nullable ErrorDTO defaultErrorDTO) {
}

@ExceptionHandler(RuntimeException.class)
protected ResponseEntity<ErrorDTO> handleException(RuntimeException error, ServerHttpRequest request) {
protected ResponseEntity<ErrorDTO> handleException(RuntimeException error) {

logClientException(error, request);
logClientException(error);

if(error instanceof ClientExceptionNoBody clientExceptionNoBody){
return ResponseEntity.status(clientExceptionNoBody.getHttpStatus()).build();
Expand All @@ -46,32 +45,25 @@ protected ResponseEntity<ErrorDTO> handleException(RuntimeException error, Serve
.body(errorDTO);
}
}
public static void logClientException(RuntimeException error, ServerHttpRequest request) {
public static void logClientException(RuntimeException error) {
Throwable unwrappedException = error.getCause() instanceof ServiceException
? error.getCause()
: error;

String clientExceptionMessage = "";
if(error instanceof ClientException clientException) {
clientExceptionMessage = ": HttpStatus %s - %s%s".formatted(
clientExceptionMessage = "HttpStatus %s - %s%s".formatted(
clientException.getHttpStatus(),
(clientException instanceof ClientExceptionWithBody clientExceptionWithBody) ? clientExceptionWithBody.getCode() + ": " : "",
clientException.getMessage()
);
}

if(!(error instanceof ClientException clientException) || clientException.isPrintStackTrace() || unwrappedException.getCause() != null){
log.error("Something went wrong handling request {}{}", getRequestDetails(request), clientExceptionMessage, unwrappedException);
log.error("Something went wrong : {}", clientExceptionMessage, unwrappedException);
} else {
log.info("A {} occurred handling request {}{} at {}",
unwrappedException.getClass().getSimpleName() ,
getRequestDetails(request),
clientExceptionMessage,
unwrappedException.getStackTrace().length > 0 ? unwrappedException.getStackTrace()[0] : "UNKNOWN");
log.info("{}",clientExceptionMessage);
}
}

public static String getRequestDetails(ServerHttpRequest request) {
return "%s %s".formatted(request.getMethod(), request.getURI());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

Expand All @@ -27,11 +26,11 @@ public ServiceExceptionHandler(ErrorManager errorManager, Map<Class<? extends Se

@SuppressWarnings("squid:S1452")
@ExceptionHandler(ServiceException.class)
protected ResponseEntity<? extends ServiceExceptionPayload> handleException(ServiceException error, ServerHttpRequest request) {
protected ResponseEntity<? extends ServiceExceptionPayload> handleException(ServiceException error) {
if (null != error.getPayload()) {
return handleBodyProvidedException(error, request);
return handleBodyProvidedException(error);
}
return errorManager.handleException(transcodeException(error), request);
return errorManager.handleException(transcodeException(error));
}

private ClientException transcodeException(ServiceException error) {
Expand All @@ -45,9 +44,9 @@ private ClientException transcodeException(ServiceException error) {
return new ClientExceptionWithBody(httpStatus, error.getCode(), error.getMessage(), error.isPrintStackTrace(), error);
}

private ResponseEntity<? extends ServiceExceptionPayload> handleBodyProvidedException(ServiceException error, ServerHttpRequest request) {
private ResponseEntity<? extends ServiceExceptionPayload> handleBodyProvidedException(ServiceException error) {
ClientException clientException = transcodeException(error);
ErrorManager.logClientException(clientException, request);
ErrorManager.logClientException(clientException);

return ResponseEntity.status(clientException.getHttpStatus())
.contentType(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
package it.gov.pagopa.common.web.exception;

import it.gov.pagopa.common.web.dto.ErrorDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.reactive.resource.NoResourceFoundException;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.server.MissingRequestValueException;

import java.util.Optional;
Expand All @@ -33,42 +32,47 @@ public ValidationExceptionHandler(@Nullable ErrorDTO templateValidationErrorDTO)
@ExceptionHandler(WebExchangeBindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorDTO handleWebExchangeBindException(
WebExchangeBindException ex, ServerHttpRequest request) {
WebExchangeBindException e) {

String message = ex.getBindingResult().getAllErrors().stream()
String message = e.getBindingResult().getAllErrors().stream()
.map(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
return String.format("[%s]: %s", fieldName, errorMessage);
}).collect(Collectors.joining("; "));

log.info("A WebExchangeBindException occurred handling request {}: HttpStatus 400 - {}",
ErrorManager.getRequestDetails(request), message);
log.debug("Something went wrong while validating http request", ex);
log.info("A WebExchangeBindException occurred : HttpStatus 400 - {}", message);
log.debug("Something went wrong while validating http request", e);

return new ErrorDTO(templateValidationErrorDTO.getCode(), message);
}

@ExceptionHandler(MissingRequestValueException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorDTO handleMissingRequestValueException(MissingRequestValueException e, ServerHttpRequest request) {

log.info("A MissingRequestValueException occurred handling request {}: HttpStatus 400 - {}",
ErrorManager.getRequestDetails(request), e.getMessage());
public ErrorDTO handleMissingRequestValueException(MissingRequestValueException e) {
log.info("A MissingRequestValueException occurred : HttpStatus 400 - Something went wrong due to a missing request value");
log.debug("Something went wrong due to a missing request value", e);

return new ErrorDTO(templateValidationErrorDTO.getCode(), templateValidationErrorDTO.getMessage());
return new ErrorDTO(templateValidationErrorDTO.getCode(), "Something went wrong due to a missing request value");
}

@ExceptionHandler(NoResourceFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorDTO handleNoResourceFoundException(NoResourceFoundException e, ServerHttpRequest request) {
public ErrorDTO handleNoResourceFoundException(NoResourceFoundException e) {

log.info("A NoResourceFoundException occurred handling request {}: HttpStatus 400 - {}",
ErrorManager.getRequestDetails(request), e.getMessage());
log.debug("Something went wrong due to a missing request value", e);
log.info("A NoResourceFoundException occurred : HttpStatus 400 - Something went wrong due to a missing static resource");
log.debug("Something went wrong due to a missing static resource", e);

return new ErrorDTO(templateValidationErrorDTO.getCode(), "Something went wrong due to a missing static resource");
}

@ExceptionHandler(MethodNotAllowedException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorDTO handleMethodNotAllowedException(MethodNotAllowedException e) {

log.info("A MethodNotAllowedException occurred : HttpStatus 405 - Request is not supported");
log.debug("Something went wrong due to a request not supported", e);

return new ErrorDTO(templateValidationErrorDTO.getCode(), templateValidationErrorDTO.getMessage());
return new ErrorDTO(templateValidationErrorDTO.getCode(), "Request is not supported");
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
package it.gov.pagopa.onboarding.citizen.configuration;


import it.gov.pagopa.common.web.exception.ClientException;
import it.gov.pagopa.common.web.exception.ClientExceptionWithBody;
import it.gov.pagopa.onboarding.citizen.constants.OnboardingCitizenConstants;
import it.gov.pagopa.onboarding.citizen.constants.CitizenConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.function.Function;

@Configuration
@Slf4j
public class ExceptionMap {

private final Map<String, Supplier<RuntimeException>> exMap = new HashMap<>();
private final Map<String, Function<String, ClientException>> exceptions = new HashMap<>();

public ExceptionMap() {
exMap.put(OnboardingCitizenConstants.ExceptionName.CITIZEN_NOT_ONBOARDED, () ->
exceptions.put(CitizenConstants.ExceptionName.CITIZEN_NOT_ONBOARDED, message ->
new ClientExceptionWithBody(
HttpStatus.NOT_FOUND,
OnboardingCitizenConstants.ExceptionCode.CITIZEN_NOT_ONBOARDED,
OnboardingCitizenConstants.ExceptionMessage.CITIZEN_NOT_ONBOARDED
CitizenConstants.ExceptionCode.CITIZEN_NOT_ONBOARDED,
message
)
);

}

public RuntimeException getException(String exceptionKey) {
if (exMap.containsKey(exceptionKey)) {
return exMap.get(exceptionKey).get();
public RuntimeException throwException(String exceptionKey, String message) {
if (exceptions.containsKey(exceptionKey)) {
return exceptions.get(exceptionKey).apply(message);
} else {
throw new IllegalArgumentException(String.format("Exception Name Not Found: %s", exceptionKey));
log.error("Exception Name Not Found: {}", exceptionKey);
return new RuntimeException();
}
}

}

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package it.gov.pagopa.onboarding.citizen.constants;

public class OnboardingCitizenConstants {
public class CitizenConstants {
public static final class ExceptionCode {

public static final String CITIZEN_NOT_ONBOARDED = "CITIZEN_NOT_ONBOARDED";
Expand All @@ -23,5 +23,5 @@ private ExceptionName() {}
}


private OnboardingCitizenConstants() {}
private CitizenConstants() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class CitizenConsentDTO {
private String hashedFiscalCode;
private String tppId;
private Boolean tppState;
private String userId;
private LocalDateTime creationDate;
private LocalDateTime lastUpdateDate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public CitizenConsentDTO map(CitizenConsent citizenConsent){
return CitizenConsentDTO.builder()
.tppState(citizenConsent.getTppState())
.tppId(citizenConsent.getTppId())
.hashedFiscalCode(citizenConsent.getHashedFiscalCode())
.userId(citizenConsent.getUserId())
.creationDate(citizenConsent.getCreationDate())
.lastUpdateDate(citizenConsent.getLastUpdateDate())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class CitizenConsent {
private String hashedFiscalCode;
private String tppId;
private Boolean tppState;
private String userId;
private LocalDateTime creationDate;
private LocalDateTime lastUpdateDate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public CitizenConsent map(CitizenConsentDTO citizenConsentDTO){
.tppState(true)
.tppId(citizenConsentDTO.getTppId())
.hashedFiscalCode(citizenConsentDTO.getHashedFiscalCode())
.userId(citizenConsentDTO.getUserId())
.build();
}
}
Loading

0 comments on commit 8eabe7b

Please sign in to comment.