huliguo
2025-05-13 a70919b4f7baab856125f36e5bd41f5ee81be680
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.cl.common.handler;
 
 
 
import com.cl.common.constant.MessageConstant;
import com.cl.common.exception.BaseException;
import com.cl.common.exception.user.InterceptorException;
import com.cl.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
import java.sql.SQLIntegrityConstraintViolationException;
 
/**
 * 全局异常处理器,处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
 
 
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
 
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result loginHandler(InterceptorException ex){
        log.error("异常信息:{}", ex.getMessage());
        return Result.error(401,ex.getMessage());
    }
 
 
    /**
     * 数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result errorHandler(MethodArgumentNotValidException e){
//        BindingResult bindingResult=exception.getBindingResult();
        String message="";
//        String message=bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
//        for(ObjectError s:e.getAllErrors()){
//            message+=s.getDefaultMessage();
//            break;
//        }
        message= String.valueOf(e.getAllErrors().get(0).getDefaultMessage());
 
        log.info("数据校验错误:{}",message);
        return Result.error(message);
    }
 
    /**
     * 处理sql异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
 
        //Duplicate entry 'zhangsan' for key 'idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username=split[2];
            String msg=username+ MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            log.error(message,ex);
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
 
    }
 
 
 
 
}