-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMethodArgumentNotValidAdviceTrait.java
More file actions
50 lines (46 loc) · 2.09 KB
/
MethodArgumentNotValidAdviceTrait.java
File metadata and controls
50 lines (46 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.ksoot.problem.spring.advice.validation;
import static com.ksoot.problem.core.ProblemConstant.CONSTRAINT_VIOLATION_CODE_CODE_PREFIX;
import static com.ksoot.problem.core.ProblemConstant.CONSTRAINT_VIOLATION_DETAIL_CODE_PREFIX;
import static com.ksoot.problem.core.ProblemConstant.CONSTRAINT_VIOLATION_TITLE_CODE_PREFIX;
import static com.ksoot.problem.core.ProblemConstant.VIOLATIONS_KEY;
import com.ksoot.problem.core.Problem;
import com.ksoot.problem.spring.config.ProblemMessageSourceResolver;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* Advice trait to handle {@link MethodArgumentNotValidException}s.
*
* @param <T> the request type
* @param <R> the response type
* @see MethodArgumentNotValidException
* @see BaseValidationAdviceTrait#defaultConstraintViolationStatus()
*/
public interface MethodArgumentNotValidAdviceTrait<T, R>
extends BaseBindingResultHandlingAdviceTrait<T, R> {
/**
* Handles {@link MethodArgumentNotValidException} and converts it into a response.
*
* @param exception the method argument not valid exception
* @param request the request
* @return the error response
*/
@ExceptionHandler
default R handleMethodArgumentNotValid(
final MethodArgumentNotValidException exception, final T request) {
List<ViolationVM> violations = handleBindingResult(exception.getBindingResult(), exception);
Map<String, Object> parameters = new LinkedHashMap<>(4);
parameters.put(VIOLATIONS_KEY, violations);
Problem problem =
toProblem(
exception,
ProblemMessageSourceResolver.of(CONSTRAINT_VIOLATION_CODE_CODE_PREFIX),
ProblemMessageSourceResolver.of(CONSTRAINT_VIOLATION_TITLE_CODE_PREFIX),
ProblemMessageSourceResolver.of(
CONSTRAINT_VIOLATION_DETAIL_CODE_PREFIX, exception.getMessage()),
parameters);
return toResponse(exception, request, defaultConstraintViolationStatus(), problem);
}
}