Files

230 lines
16 KiB
HTML

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>ValidationExceptionHandler.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">project-auth-server</a> &gt; <a href="index.source.html" class="el_package">com.project.auth.presentation.support.exception</a> &gt; <span class="el_source">ValidationExceptionHandler.java</span></div><h1>ValidationExceptionHandler.java</h1><pre class="source lang-java linenums">package com.project.auth.presentation.support.exception;
import com.project.auth.presentation.support.response.ApiResult;
import com.project.auth.presentation.support.response.ApiResultFactory;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
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;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class ValidationExceptionHandler {
/**
* 필드와 연결되지 않은 클래스 레벨/cross-field 검증 실패(예: DTO의 {@code @AssertTrue},
* 커스텀 클래스 레벨 {@code ConstraintValidator})를 담는 버킷 키.
*
* 이 버킷이 없으면 ObjectError가 조용히 폐기되어 클라이언트는 {@code errors: {}}만 받고
* 어디가 잘못됐는지 알 수 없다.
*/
public static final String GLOBAL_ERROR_KEY = &quot;__global__&quot;;
/**
* {@code getDefaultMessage()}와 {@code error.code()}가 모두 null/공백인 경우의 폴백 메시지.
*
* Bean Validation은 MessageSource로 해석되는 메시지 코드만 정의된 케이스를 허용하며,
* 이때 getDefaultMessage()는 null을 반환할 수 있다. 이 sentinel이 없으면 응답 errors에
* {@code [null]} 항목이 그대로 들어간다.
*/
static final String UNRESOLVED_VIOLATION_MESSAGE = &quot;validation failed&quot;;
<span class="fc" id="L48"> private static final Logger log = LoggerFactory.getLogger(ValidationExceptionHandler.class);</span>
private final ApiResultFactory apiResultFactory;
<span class="fc" id="L52"> public ValidationExceptionHandler(ApiResultFactory apiResultFactory) {</span>
<span class="fc" id="L53"> this.apiResultFactory = apiResultFactory;</span>
<span class="fc" id="L54"> }</span>
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity&lt;ApiResult&lt;Void&gt;&gt; handleValidationException(
MethodArgumentNotValidException exception
) {
<span class="fc" id="L60"> Map&lt;String, List&lt;String&gt;&gt; errors = new LinkedHashMap&lt;&gt;();</span>
<span class="fc bfc" id="L61" title="All 2 branches covered."> for (FieldError fieldError : exception.getBindingResult().getFieldErrors()) {</span>
<span class="fc" id="L62"> errors.computeIfAbsent(fieldFieldToJsonPointer(fieldError.getField()), k -&gt; new ArrayList&lt;&gt;())</span>
<span class="fc" id="L63"> .add(resolveMessage(fieldError.getDefaultMessage(), fieldError.getCode()));</span>
<span class="fc" id="L64"> }</span>
<span class="fc bfc" id="L65" title="All 2 branches covered."> for (ObjectError globalError : exception.getBindingResult().getGlobalErrors()) {</span>
<span class="fc" id="L66"> errors.computeIfAbsent(GLOBAL_ERROR_KEY, k -&gt; new ArrayList&lt;&gt;())</span>
<span class="fc" id="L67"> .add(resolveMessage(globalError.getDefaultMessage(), globalError.getCode()));</span>
<span class="fc" id="L68"> }</span>
<span class="fc" id="L70"> log.warn(&quot;Validation failed: {}&quot;, errors);</span>
<span class="fc" id="L72"> return ResponseEntity.status(ApiErrorHttpStatusMapper.map(PresentationErrorCode.INVALID_INPUT))</span>
<span class="fc" id="L73"> .body(apiResultFactory.failure(</span>
<span class="fc" id="L74"> PresentationErrorCode.INVALID_INPUT.code(),</span>
<span class="fc" id="L75"> PresentationErrorCode.INVALID_INPUT.message(),</span>
errors
));
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity&lt;ApiResult&lt;Void&gt;&gt; handleConstraintViolationException(
ConstraintViolationException exception
) {
<span class="fc" id="L84"> Map&lt;String, List&lt;String&gt;&gt; errors = new LinkedHashMap&lt;&gt;();</span>
<span class="fc bfc" id="L85" title="All 2 branches covered."> for (ConstraintViolation&lt;?&gt; violation : exception.getConstraintViolations()) {</span>
<span class="fc" id="L86"> String pointer = toJsonPointer(violation.getPropertyPath());</span>
<span class="fc" id="L87"> errors.computeIfAbsent(pointer, k -&gt; new ArrayList&lt;&gt;())</span>
<span class="fc" id="L88"> .add(resolveMessage(violation.getMessage(), null));</span>
<span class="fc" id="L89"> }</span>
<span class="fc" id="L91"> log.warn(&quot;Constraint violation: {}&quot;, errors);</span>
<span class="fc" id="L93"> return ResponseEntity.status(ApiErrorHttpStatusMapper.map(PresentationErrorCode.CONSTRAINT_VIOLATION))</span>
<span class="fc" id="L94"> .body(apiResultFactory.failure(</span>
<span class="fc" id="L95"> PresentationErrorCode.CONSTRAINT_VIOLATION.code(),</span>
<span class="fc" id="L96"> PresentationErrorCode.CONSTRAINT_VIOLATION.message(),</span>
errors
));
}
@ExceptionHandler(HandlerMethodValidationException.class)
public ResponseEntity&lt;ApiResult&lt;Void&gt;&gt; handleHandlerMethodValidationException(
HandlerMethodValidationException exception
) {
<span class="fc" id="L105"> Map&lt;String, List&lt;String&gt;&gt; errors = new LinkedHashMap&lt;&gt;();</span>
<span class="fc" id="L106"> int unnamedCounter = 0;</span>
<span class="fc bfc" id="L107" title="All 2 branches covered."> for (var result : exception.getValueResults()) {</span>
<span class="fc" id="L108"> String paramName = result.getMethodParameter().getParameterName();</span>
String key;
<span class="fc bfc" id="L110" title="All 2 branches covered."> if (paramName != null) {</span>
<span class="fc" id="L111"> key = fieldFieldToJsonPointer(paramName);</span>
} else {
<span class="fc" id="L113"> key = fieldFieldToJsonPointer(&quot;unknown_&quot; + result.getMethodParameter().getParameterIndex());</span>
<span class="fc" id="L114"> unnamedCounter++;</span>
}
<span class="fc bfc" id="L116" title="All 2 branches covered."> for (MessageSourceResolvable error : result.getResolvableErrors()) {</span>
<span class="fc" id="L117"> String[] codes = error.getCodes();</span>
<span class="pc bpc" id="L118" title="2 of 4 branches missed."> String firstCode = codes != null &amp;&amp; codes.length &gt; 0 ? codes[0] : null;</span>
<span class="fc" id="L119"> errors.computeIfAbsent(key, k -&gt; new ArrayList&lt;&gt;())</span>
<span class="fc" id="L120"> .add(resolveMessage(error.getDefaultMessage(), firstCode));</span>
<span class="fc" id="L121"> }</span>
<span class="fc" id="L122"> }</span>
<span class="fc bfc" id="L123" title="All 2 branches covered."> if (unnamedCounter &gt; 0) {</span>
<span class="fc" id="L124"> log.warn(&quot;Handler method validation: {} unnamed parameter(s); compile with -parameters to recover names&quot;,</span>
<span class="fc" id="L125"> unnamedCounter);</span>
}
<span class="fc" id="L128"> log.warn(&quot;Handler method validation failed: {}&quot;, errors);</span>
<span class="fc" id="L130"> return ResponseEntity.status(ApiErrorHttpStatusMapper.map(PresentationErrorCode.INVALID_PARAMETER))</span>
<span class="fc" id="L131"> .body(apiResultFactory.failure(</span>
<span class="fc" id="L132"> PresentationErrorCode.INVALID_PARAMETER.code(),</span>
<span class="fc" id="L133"> PresentationErrorCode.INVALID_PARAMETER.message(),</span>
errors
));
}
/**
* Bean Validation의 propertyPath를 JSON Pointer(RFC 6901) 형식으로 변환한다.
* 예) {@code users[0].email} -&gt; {@code /users/0/email}
*
* 서로 다른 파라미터가 우연히 같은 필드명으로 끝나도 충돌이 발생하지 않으며,
* 클라이언트 입장에서 모호함이 없는 형식이다.
* 메서드 파라미터 접두사(예: {@code findUser.id})는 출처 파라미터를 식별하므로
* 첫 pointer 세그먼트로 보존한다.
*/
private static String toJsonPointer(Path path) {
<span class="fc" id="L148"> StringBuilder builder = new StringBuilder();</span>
<span class="fc bfc" id="L149" title="All 2 branches covered."> for (Path.Node node : path) {</span>
<span class="fc" id="L150"> String name = node.getName();</span>
<span class="pc bpc" id="L151" title="1 of 2 branches missed."> if (name == null) {</span>
<span class="nc" id="L152"> continue;</span>
}
<span class="fc" id="L154"> builder.append('/').append(escapeJsonPointerSegment(name));</span>
<span class="fc" id="L155"> Integer index = node.getIndex();</span>
<span class="pc bpc" id="L156" title="1 of 2 branches missed."> if (index != null) {</span>
<span class="nc" id="L157"> builder.append('/').append(index);</span>
<span class="pc bpc" id="L158" title="1 of 2 branches missed."> } else if (node.getKey() != null) {</span>
<span class="nc" id="L159"> builder.append('/').append(escapeJsonPointerSegment(String.valueOf(node.getKey())));</span>
}
<span class="fc" id="L161"> }</span>
<span class="pc bpc" id="L162" title="1 of 2 branches missed."> return builder.length() == 0 ? &quot;/&quot; : builder.toString();</span>
}
private static String escapeJsonPointerSegment(String segment) {
<span class="fc" id="L166"> return segment.replace(&quot;~&quot;, &quot;~0&quot;).replace(&quot;/&quot;, &quot;~1&quot;);</span>
}
/**
* Spring {@code BindingResult.FieldError#getField()} 형식(예: {@code user.email},
* {@code items[0].name})을 JSON Pointer(RFC 6901)로 변환한다.
* ConstraintViolationException 핸들러와 키 형식을 통일하여, 응답 errors 맵의 키 규약을
* 단일화한다(클라이언트가 두 가지 형식을 분기 처리할 필요가 없게 한다).
*/
static String fieldFieldToJsonPointer(String field) {
<span class="fc bfc" id="L176" title="All 4 branches covered."> if (field == null || field.isEmpty()) {</span>
<span class="fc" id="L177"> return &quot;/&quot;;</span>
}
<span class="fc" id="L179"> StringBuilder builder = new StringBuilder();</span>
<span class="fc" id="L180"> int index = 0;</span>
<span class="fc" id="L181"> int length = field.length();</span>
<span class="fc bfc" id="L182" title="All 2 branches covered."> while (index &lt; length) {</span>
<span class="fc" id="L183"> char ch = field.charAt(index);</span>
<span class="fc bfc" id="L184" title="All 2 branches covered."> if (ch == '.') {</span>
<span class="fc" id="L185"> index++;</span>
<span class="fc" id="L186"> continue;</span>
}
<span class="fc bfc" id="L188" title="All 2 branches covered."> if (ch == '[') {</span>
<span class="fc" id="L189"> int end = field.indexOf(']', index);</span>
<span class="pc bpc" id="L190" title="1 of 2 branches missed."> if (end == -1) {</span>
<span class="nc" id="L191"> builder.append('/').append(escapeJsonPointerSegment(field.substring(index)));</span>
<span class="nc" id="L192"> break;</span>
}
<span class="fc" id="L194"> builder.append('/').append(escapeJsonPointerSegment(field.substring(index + 1, end)));</span>
<span class="fc" id="L195"> index = end + 1;</span>
<span class="fc" id="L196"> continue;</span>
}
<span class="fc" id="L198"> int nextDot = field.indexOf('.', index);</span>
<span class="fc" id="L199"> int nextBracket = field.indexOf('[', index);</span>
<span class="fc" id="L200"> int next = minNonNegative(nextDot, nextBracket);</span>
<span class="fc bfc" id="L201" title="All 2 branches covered."> if (next == -1) {</span>
<span class="fc" id="L202"> next = length;</span>
}
<span class="fc" id="L204"> builder.append('/').append(escapeJsonPointerSegment(field.substring(index, next)));</span>
<span class="fc" id="L205"> index = next;</span>
<span class="fc" id="L206"> }</span>
<span class="pc bpc" id="L207" title="1 of 2 branches missed."> return builder.length() == 0 ? &quot;/&quot; : builder.toString();</span>
}
private static int minNonNegative(int a, int b) {
<span class="fc bfc" id="L211" title="All 2 branches covered."> if (a &lt; 0) {</span>
<span class="fc" id="L212"> return b;</span>
}
<span class="fc bfc" id="L214" title="All 2 branches covered."> if (b &lt; 0) {</span>
<span class="fc" id="L215"> return a;</span>
}
<span class="fc" id="L217"> return Math.min(a, b);</span>
}
private static String resolveMessage(String defaultMessage, String fallbackCode) {
<span class="pc bpc" id="L221" title="1 of 4 branches missed."> if (defaultMessage != null &amp;&amp; !defaultMessage.isBlank()) {</span>
<span class="fc" id="L222"> return defaultMessage;</span>
}
<span class="pc bpc" id="L224" title="2 of 4 branches missed."> if (fallbackCode != null &amp;&amp; !fallbackCode.isBlank()) {</span>
<span class="fc" id="L225"> return fallbackCode;</span>
}
<span class="nc" id="L227"> return UNRESOLVED_VIOLATION_MESSAGE;</span>
}
}
</pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.14.202510111229</span></div></body></html>