zainali5120
2020-09-25 286ea89f5f6cade73276f865effa5dcd2b19406d
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
package com.xcong.excoin.configurations;
 
import com.xcong.excoin.common.exception.GlobalException;
import com.xcong.excoin.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
import javax.validation.ValidationException;
 
/**
 * @author wzy
 * @date 2020-05-08 15:40
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
 
    /**
     * 方法参数校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result handleException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        FieldError fieldError = e.getBindingResult().getFieldError();
        if (fieldError != null) {
            return Result.fail(fieldError.getDefaultMessage());
        } else {
            return Result.fail("参数校验失败");
        }
    }
 
 
    @ExceptionHandler(value = {ValidationException.class})
    public Result handleException(ValidationException e) {
        log.error(e.getMessage(), e);
        return null;
    }
 
    @ExceptionHandler(value = {DuplicateKeyException.class})
    public Result handleException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return null;
    }
 
 
    /**
     * spring security 账户密码验证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = { BadCredentialsException.class })
    public Result handleException(BadCredentialsException e) {
        log.error(e.getMessage(), e);
        return Result.fail("用户名或密码错误");
    }
 
    @ExceptionHandler(value = {GlobalException.class})
    public Result handleException(GlobalException e) {
        return Result.fail(e.getMessage());
    }
 
    @ExceptionHandler(value = {Exception.class})
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail("系统异常");
    }
 
}