Renamed various classes to follow the "controlers" package structure for better organization and consistency. Added `ControllerExceptionHandler` to manage validation exceptions globally and improve error logging.
48 lines
1.9 KiB
Java
48 lines
1.9 KiB
Java
package com.alttd.forms.controlers;
|
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.http.HttpStatus;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.validation.FieldError;
|
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
@ControllerAdvice
|
|
public class ControllerExceptionHandler {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
|
|
|
|
public ControllerExceptionHandler() {
|
|
logger.info("ControllerExceptionHandler initialized"); // Ensure this gets logged
|
|
}
|
|
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
|
logger.debug("invalid request", ex);
|
|
Map<String, String> errors = new HashMap<>();
|
|
ex.getBindingResult().getAllErrors().forEach((error) -> {
|
|
String fieldName = ((FieldError) error).getField();
|
|
String errorMessage = error.getDefaultMessage();
|
|
errors.put(fieldName, errorMessage);
|
|
});
|
|
if (logger.isDebugEnabled()) {
|
|
try {
|
|
String errorsAsString = new ObjectMapper().writeValueAsString(errors);
|
|
logger.debug("Invalid parameters\n{}", errorsAsString);
|
|
} catch (JsonProcessingException e) {
|
|
logger.warn("Failed to parse errors to json", e);
|
|
}
|
|
}
|
|
return ResponseEntity.badRequest().body(errors);
|
|
}
|
|
}
|