KRYSTALM7 commented on code in PR #171:
URL:
https://github.com/apache/fineract-loan-origination/pull/171#discussion_r4293518254
##########
src/main/java/org/apache/fineract/los/exception/GlobalExceptionHandler.java:
##########
@@ -19,25 +19,73 @@
package org.apache.fineract.los.exception;
+import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.los.statemachine.LoanStateTransitionException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+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.method.annotation.HandlerMethodValidationException;
/**
* Centralised mapping from LOS exceptions to HTTP responses.
*
* <p>Every custom exception in {@code org.apache.fineract.los.exception} is
handled here — no
* controller should need its own try/catch for these. Anything unmapped falls
through to a generic
- * 500 with the exception message, which is acceptable for a POC but should be
tightened (message
- * scrubbing) before any production use.
+ * 500 without exposing exception details.
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
+ @ExceptionHandler(MethodArgumentNotValidException.class)
+ public ResponseEntity<ErrorResponse> handleValidation(final
MethodArgumentNotValidException ex) {
+ final String message =
+ ex.getBindingResult().getAllErrors().stream()
+ .map(
+ error ->
+ error instanceof FieldError fieldError
+ ? fieldError.getField() + ": " +
fieldError.getDefaultMessage()
+ : error.getDefaultMessage())
+ .sorted()
+ .collect(Collectors.joining("; "));
+ return build(HttpStatus.BAD_REQUEST, message);
+ }
+
+ @ExceptionHandler(HandlerMethodValidationException.class)
+ public ResponseEntity<ErrorResponse> handleMethodValidation(
+ final HandlerMethodValidationException ex) {
+ if (ex.isForReturnValue()) {
+ return handleUnexpected(ex);
+ }
+
+ final String message =
+ ex.getParameterValidationResults().stream()
Review Comment:
Could we consider a fallback when "getMethodParameter().getParameterName()"
returns "null"? Parameter names may not always be available depending on
compiler configuration. A fallback such as the parameter index would help keep
validation messages meaningful across different environments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]