From de12494bbd11bf6dbd7746df20a6b23320c0b440 Mon Sep 17 00:00:00 2001 From: yjxx <1055683039@qq.com> Date: Thu, 24 Oct 2024 22:23:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=8F=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../interceptors/GlobalExceptionHandler.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/jty/expressdistributionsystem/interceptors/GlobalExceptionHandler.java b/src/main/java/jty/expressdistributionsystem/interceptors/GlobalExceptionHandler.java index 6e55c87..97bf89c 100644 --- a/src/main/java/jty/expressdistributionsystem/interceptors/GlobalExceptionHandler.java +++ b/src/main/java/jty/expressdistributionsystem/interceptors/GlobalExceptionHandler.java @@ -1,15 +1,22 @@ package jty.expressdistributionsystem.interceptors; -import jty.expressdistributionsystem.entity.Result; -import org.springframework.util.StringUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import java.util.HashMap; +import java.util.Map; + @RestControllerAdvice public class GlobalExceptionHandler { - @ExceptionHandler(Exception.class) - public Result handleException(Exception e){ - e.printStackTrace(); - return new Result(500, StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败", ""); + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions(MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getFieldErrors().forEach(error -> + errors.put(error.getField(), error.getDefaultMessage()) + ); + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } }