GlobalExceptionHandler.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.aijiuyi.admin.common;
  2. import org.springframework.http.HttpStatus;
  3. import org.springframework.security.access.AccessDeniedException;
  4. import org.springframework.security.authentication.BadCredentialsException;
  5. import org.springframework.validation.BindException;
  6. import org.springframework.web.bind.MethodArgumentNotValidException;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseStatus;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10. /**
  11. * 全局异常处理:业务异常、参数校验、认证与通用异常的统一 JSON 响应。
  12. */
  13. @RestControllerAdvice
  14. public class GlobalExceptionHandler {
  15. @ExceptionHandler(BusinessException.class)
  16. @ResponseStatus(HttpStatus.OK)
  17. public ApiResponse<Void> handleBusiness(BusinessException e) {
  18. return ApiResponse.fail(e.getCode(), e.getMessage());
  19. }
  20. @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
  21. @ResponseStatus(HttpStatus.BAD_REQUEST)
  22. public ApiResponse<Void> handleValidation(Exception e) {
  23. String msg = e.getMessage();
  24. if (e instanceof MethodArgumentNotValidException) {
  25. MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
  26. if (ex.getBindingResult().getFieldError() != null) {
  27. msg = ex.getBindingResult().getFieldError().getDefaultMessage();
  28. }
  29. }
  30. return ApiResponse.fail(400, msg);
  31. }
  32. @ExceptionHandler(BadCredentialsException.class)
  33. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  34. public ApiResponse<Void> handleBadCredentials(BadCredentialsException e) {
  35. return ApiResponse.fail(401, "用户名或密码错误");
  36. }
  37. @ExceptionHandler(AccessDeniedException.class)
  38. @ResponseStatus(HttpStatus.FORBIDDEN)
  39. public ApiResponse<Void> handleDenied(AccessDeniedException e) {
  40. return ApiResponse.fail(403, "无权限");
  41. }
  42. @ExceptionHandler(Exception.class)
  43. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  44. public ApiResponse<Void> handleOther(Exception e) {
  45. return ApiResponse.fail(500, e.getMessage() != null ? e.getMessage() : "服务器错误");
  46. }
  47. }