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 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()); } }