| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- 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<Void> handleBusiness(BusinessException e) {
- return ApiResponse.fail(e.getCode(), e.getMessage());
- }
- @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
- @ResponseStatus(HttpStatus.BAD_REQUEST)
- public ApiResponse<Void> 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<Void> handleBadCredentials(BadCredentialsException e) {
- return ApiResponse.fail(401, "用户名或密码错误");
- }
- @ExceptionHandler(AccessDeniedException.class)
- @ResponseStatus(HttpStatus.FORBIDDEN)
- public ApiResponse<Void> handleDenied(AccessDeniedException e) {
- return ApiResponse.fail(403, "无权限");
- }
- @ExceptionHandler(Exception.class)
- @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
- public ApiResponse<Void> handleOther(Exception e) {
- return ApiResponse.fail(500, e.getMessage() != null ? e.getMessage() : "服务器错误");
- }
- }
|