package com.sinata.appointment.common;
|
|
import cn.dev33.satoken.exception.NotLoginException;
|
import cn.dev33.satoken.exception.NotPermissionException;
|
import com.sinata.appointment.constants.HttpBizCode;
|
import com.sinata.appointment.exception.BizException;
|
|
import cn.dev33.satoken.exception.SaTokenException;
|
import jakarta.validation.ConstraintViolationException;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
@Slf4j
|
@RestControllerAdvice
|
public class GlobalExceptionHandler {
|
|
@ExceptionHandler(BizException.class)
|
public Result<Void> handleBiz(BizException e) {
|
return ResultUtil.error(e.getCode(), e.getMessage());
|
}
|
|
@ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
|
public Result<Void> handleValidation(Exception e) {
|
String msg =
|
e instanceof MethodArgumentNotValidException mn
|
? mn.getBindingResult().getFieldError() != null
|
? mn.getBindingResult().getFieldError().getDefaultMessage()
|
: e.getMessage()
|
: e.getMessage();
|
return ResultUtil.error(HttpBizCode.BAD_REQUEST, msg != null ? msg : "参数错误");
|
}
|
|
|
@ExceptionHandler(SaTokenException.class)
|
public Result<Void> handleSaToken(SaTokenException e) {
|
if (e instanceof NotPermissionException){
|
log.warn("satoken forbidden: {}", safeMessage(e));
|
return ResultUtil.error(HttpBizCode.FORBIDDEN, "无权限访问");
|
}
|
if (e instanceof NotLoginException notLogin
|
&& NotLoginException.KICK_OUT.equals(notLogin.getType())) {
|
log.warn("satoken unauthorized: type={} message={}", notLogin.getType(), safeMessage(e));
|
return ResultUtil.error(HttpBizCode.UNAUTHORIZED, "账号已被禁用,请重新登录");
|
}
|
if (e instanceof NotLoginException notLogin) {
|
log.warn("satoken unauthorized: type={} message={}", notLogin.getType(), safeMessage(e));
|
return ResultUtil.error(HttpBizCode.UNAUTHORIZED, "账号信息已过期,请重新登录");
|
}
|
log.warn("satoken error: {} message={}", e.getClass().getSimpleName(), safeMessage(e));
|
return ResultUtil.error(HttpBizCode.UNAUTHORIZED, "账号信息已过期,请重新登录");
|
}
|
|
private String safeMessage(Exception e) {
|
String message = e.getMessage();
|
return message == null || message.isBlank() ? "-" : message;
|
}
|
|
@ExceptionHandler(Exception.class)
|
public Result<Void> handleOther(Exception e) {
|
log.error("Unhandled error", e);
|
return ResultUtil.error(HttpBizCode.INTERNAL_ERROR, "系统繁忙,请稍后重试");
|
}
|
}
|