package space.anyi.petServiceManagementSystem.server.config; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import space.anyi.petServiceManagementSystem.server.common.BusinessException; import space.anyi.petServiceManagementSystem.server.common.ForbiddenException; import space.anyi.petServiceManagementSystem.server.common.R; import space.anyi.petServiceManagementSystem.server.common.ResourceNotFoundException; import space.anyi.petServiceManagementSystem.server.common.UnauthorizedException; import java.util.Objects; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleBusinessException(BusinessException e) { return R.error(e.getCode(), e.getMessage()); } @ExceptionHandler(UnauthorizedException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public R handleUnauthorized(UnauthorizedException e) { return R.error(e.getCode(), e.getMessage()); } @ExceptionHandler(ForbiddenException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public R handleForbidden(ForbiddenException e) { return R.error(e.getCode(), e.getMessage()); } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public R handleNotFound(ResourceNotFoundException e) { return R.error(e.getCode(), e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleValidation(MethodArgumentNotValidException e) { String msg = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(); return R.error(400, msg); } @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleBindException(BindException e) { String msg = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(); return R.error(400, msg); } @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleMissingParam(MissingServletRequestParameterException e) { return R.error(400, "缺少必填参数: " + e.getParameterName()); } @ExceptionHandler(DuplicateKeyException.class) @ResponseStatus(HttpStatus.CONFLICT) public R handleDuplicateKey(DuplicateKeyException e) { return R.error(409, "数据重复,请检查唯一字段"); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public R handleException(Exception e) { e.printStackTrace(); return R.error(500, "服务器内部错误"); } }