From 1acf9a48021d0af1d81fdf3ed8fcf8dffd020f6b Mon Sep 17 00:00:00 2001 From: hongjli <3117313295@qq.com> Date: 星期二, 15 四月 2025 14:20:51 +0800 Subject: [PATCH] 登录,注册,获取用户信息---接口 --- src/main/java/com/weiwojc/exception/GlobalExceptionHandler.java | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 47 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/weiwojc/exception/GlobalExceptionHandler.java b/src/main/java/com/weiwojc/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..45e377d --- /dev/null +++ b/src/main/java/com/weiwojc/exception/GlobalExceptionHandler.java @@ -0,0 +1,47 @@ +package com.weiwojc.exception; + +import com.weiwojc.model.common.Result; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.LockedException; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.List; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(RuntimeException.class) + public Result<?> handleRuntimeException(RuntimeException e) { + return Result.badRequest(e.getMessage()); + } + + @ExceptionHandler(BadCredentialsException.class) + public Result<?> handleBadCredentialsException(BadCredentialsException e) { + return Result.unauthorized(e.getMessage()); + } + + @ExceptionHandler(LockedException.class) + public Result<?> handleLockedException(LockedException e) { + return Result.forbidden(e.getMessage()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public Result<?> handleValidationException(MethodArgumentNotValidException e) { + BindingResult bindingResult = e.getBindingResult(); + List<FieldError> fieldErrors = bindingResult.getFieldErrors(); + String errorMessage = fieldErrors.stream() + .map(FieldError::getDefaultMessage) + .collect(Collectors.joining(", ")); + return Result.badRequest(errorMessage); + } + + @ExceptionHandler(Exception.class) + public Result<?> handleException(Exception e) { + return Result.error("鏈嶅姟鍣ㄥ唴閮ㄩ敊璇細" + e.getMessage()); + } +} \ No newline at end of file -- Gitblit v1.9.3