longz
2026-04-21 58c73134fb1ce10c1ea1d95ee66d8c89557d7dee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.sinata.appointment.common;
 
import cn.dev33.satoken.exception.NotLoginException;
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) {
        log.error("satoken error", e);
        if (e instanceof NotLoginException notLogin
                && NotLoginException.KICK_OUT.equals(notLogin.getType())) {
            return ResultUtil.error(HttpBizCode.UNAUTHORIZED, "账号已被禁用,请重新登录");
        }
        return ResultUtil.error(HttpBizCode.UNAUTHORIZED, "账号信息已过期,请重新登录");
    }
 
    @ExceptionHandler(Exception.class)
    public Result<Void> handleOther(Exception e) {
        log.error("Unhandled error", e);
        return ResultUtil.error(HttpBizCode.INTERNAL_ERROR, "系统繁忙,请稍后重试");
    }
}