package com.aijiuyi.admin.common; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * 全局异常处理:业务异常、参数校验、认证与通用异常的统一 JSON 响应。 */ @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) @ResponseStatus(HttpStatus.OK) public ApiResponse handleBusiness(BusinessException e) { return ApiResponse.fail(e.getCode(), e.getMessage()); } @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ApiResponse handleValidation(Exception e) { String msg = e.getMessage(); if (e instanceof MethodArgumentNotValidException) { MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e; if (ex.getBindingResult().getFieldError() != null) { msg = ex.getBindingResult().getFieldError().getDefaultMessage(); } } return ApiResponse.fail(400, msg); } @ExceptionHandler(BadCredentialsException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ApiResponse handleBadCredentials(BadCredentialsException e) { return ApiResponse.fail(401, "用户名或密码错误"); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public ApiResponse handleDenied(AccessDeniedException e) { return ApiResponse.fail(403, "无权限"); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ApiResponse handleOther(Exception e) { return ApiResponse.fail(500, e.getMessage() != null ? e.getMessage() : "服务器错误"); } }