Unverified Commit 7a7fb53e authored by jiandan217's avatar jiandan217 Committed by GitHub
Browse files

perf: 优化接口数据验证异常 message (#771)

parent e0af08eb
...@@ -23,10 +23,11 @@ import me.zhengjie.utils.ThrowableUtil; ...@@ -23,10 +23,11 @@ import me.zhengjie.utils.ThrowableUtil;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Objects;
import static org.springframework.http.HttpStatus.*; import static org.springframework.http.HttpStatus.*;
/** /**
...@@ -95,11 +96,10 @@ public class GlobalExceptionHandler { ...@@ -95,11 +96,10 @@ public class GlobalExceptionHandler {
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息 // 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e)); log.error(ThrowableUtil.getStackTrace(e));
String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\."); ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage(); String message = objectError.getDefaultMessage();
String msg = "不能为空"; if (objectError instanceof FieldError) {
if(msg.equals(message)){ message = ((FieldError) objectError).getField() + ": " + message;
message = str[1] + ":" + message;
} }
return buildResponseEntity(ApiError.error(message)); return buildResponseEntity(ApiError.error(message));
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment