Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow override of the message property for a violation exception #105

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 52 additions & 2 deletions src/docs/asciidoc/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -472,8 +472,58 @@ The response JSON:

==== General override of error messages

By using `error.handling.messages` property, it is possible to globally set an error message for a certain exception.
This is most useful for the validation messages.
By using `error.handling.messages` property, it is possible to globally set an error message for a certain exception or a certain validation annotation.

===== Exception

Suppose you have this defined:

[source,properties]
----
error.handling.messages.com.company.application.user.UserNotFoundException=The user was not found
----

The response JSON:

[source,json]
----
{
"code": "USER_NOT_FOUND",
"message": "The user was not found" //<.>
}
----

<.> The output uses the configured override.

This can also be used for exception types that are not part of your own application.

For example:

[source,properties]
----
error.handling.messages.jakarta.validation.ConstraintViolationException=There was a validation failure.
----

Will output the following JSON:

[source,json]
----
{
"code": "VALIDATION_FAILED",
"message": "There was a validation failure.",
"fieldErrors": [
{
"code": "INVALID_SIZE",
"property": "name",
"message": "size must be between 10 and 2147483647",
"rejectedValue": "",
"path": "name"
}
]
}
----

===== Validation annotation

Suppose you have this defined:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@
import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorCodeMapper;
import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorMessageMapper;
import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.HttpStatusMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ElementKind;
import jakarta.validation.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.util.Comparator;
import java.util.Optional;
Expand Down Expand Up @@ -136,6 +135,7 @@ private String getMessage(ConstraintViolation<?> constraintViolation) {
}

private String getMessage(ConstraintViolationException exception) {
return "Validation failed. Error count: " + exception.getConstraintViolations().size();
return errorMessageMapper.getErrorMessageIfConfiguredInProperties(exception)
.orElseGet(() -> "Validation failed. Error count: " + exception.getConstraintViolations().size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import io.github.wimdeblauwe.errorhandlingspringbootstarter.ErrorHandlingProperties;

import java.util.Optional;

import static org.springframework.util.StringUtils.hasText;

/**
Expand All @@ -22,6 +24,10 @@ public String getErrorMessage(Throwable exception) {
return exception.getMessage();
}

public Optional<String> getErrorMessageIfConfiguredInProperties(Throwable exception) {
return Optional.ofNullable(getErrorMessageFromProperties(exception.getClass()));
}

public String getErrorMessage(String fieldSpecificCode, String code, String defaultMessage) {
if (properties.getMessages().containsKey(fieldSpecificCode)) {
return properties.getMessages().get(fieldSpecificCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,20 @@ void testErrorCodeOverride(@Autowired ErrorHandlingProperties properties) throws
;
}

@Test
@WithMockUser
void testErrorMessageOverride(@Autowired ErrorHandlingProperties properties) throws Exception {
properties.getMessages().put("jakarta.validation.ConstraintViolationException", "There was a validation failure.");
mockMvc.perform(post("/test/validation")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"value2\": \"\"}")
.with(csrf()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("code").value("VALIDATION_FAILED"))
.andExpect(jsonPath("message").value("There was a validation failure."))
;
}

@Test
@WithMockUser
void testFieldErrorCodeOverride(@Autowired ErrorHandlingProperties properties) throws Exception {
Expand Down
Loading