tuannqhe151337 / fin-planning-backend

Capstone backend (Spring Boot)
0 stars 1 forks source link

Handler exception method bug if message contains many parts that separates by commas , it only get the first part #235

Closed giangdvhe163178 closed 3 months ago

giangdvhe163178 commented 3 months ago

name reason how to fix assignees
:bug: Handler exception method bug if message contains many parts that separates by commas , it only get the first part Return Missing message Fix handler method giangdvhe163178

:bug: Bug Report

Current Behavior Handler exception method bug if message contains many parts that separates by commas , it only get the first part image

Steps to reproduce

Input Code GlobalExceptionHandler.java

 private List<ExceptionResponse> parseMessageToListExceptionResponse(String errorMessage) {
        String[] errors = errorMessage.split(",");
        List<ExceptionResponse> exceptionResponseList = new ArrayList<>();
        for (String s : errors) {
            String[] parts = s.trim().split(": ");
            if (parts.length == 2) {
                String fieldName = parts[0].substring(parts[0].lastIndexOf(".") + 1);
                String errorMessageText = parts[1];
                ExceptionResponse exception = ExceptionResponse.builder()
                        .field(fieldName).message(errorMessageText)
                        .build();
                exceptionResponseList.add(exception);
            }
        }

        return exceptionResponseList;
    }

Change to :

private List<ExceptionResponse> parseMessageToListExceptionResponse(String errorMessage) {
    List<ExceptionResponse> errorList = new ArrayList<>();
    // Biểu thức chính quy để tìm field và message
    Pattern pattern = Pattern.compile("(\\w+\\.\\w+\\.\\w+):\\s(.*?)(?=(?:\\w+\\.\\w+\\.\\w+:\\s|$))");
    Matcher matcher = pattern.matcher(errorMessage);

    while (matcher.find()) {
        String field = matcher.group(1).substring(matcher.group(1).lastIndexOf('.') + 1);
        String message = matcher.group(2).trim(); // Loại bỏ khoảng trắng và dấu phẩy thừa
        if (message.endsWith(",")) {
            message = message.substring(0, message.length() - 1).trim(); // Loại bỏ dấu phẩy thừa nếu có
        }
        errorList.add(new ExceptionResponse(field, message));
    }

    return errorList;
}

Expected behavior/code

[
    {
        "field": "newPassword",
        "message": "New password must be at least 8 characters long, contain at least one special character, one uppercase letter, and one lowercase letter"
    }
]

Environment

Possible Solution

Additional context/Screenshots Add any other context about the problem here. If applicable, add screenshots to help explain.

giangdvhe163178 commented 3 months ago

Solved: image