ab
2024-11-04 09d882262f530ded672f1c01fb65a1fefa00d52d
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
package com.nova.sankuai.infra.exception;
 
import com.nova.sankuai.infra.constants.ResultCode;
import com.nova.sankuai.infra.config.CommonException;
import com.nova.sankuai.infra.utils.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
import javax.servlet.http.HttpServletRequest;
 
 
/**
 * @author weikangdi
 */
@Slf4j
@RestControllerAdvice
@Component
public class ExceptionHandlerAdvice {
 
    private static final Logger logger = LoggerFactory.getLogger("exceptionLogger");
 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleMethodArguemntNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        logger.error("参数或者语法不对", e);
        return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.BAD_REQUEST, e.getBindingResult().getFieldError().getDefaultMessage()));
    }
 
    /**
     * 权限不足
     */
    @ExceptionHandler(InsufficientAuthenticationException.class)
    public ResponseEntity handleInsufficientAuthenticationException(InsufficientAuthenticationException e,
                                                                    HttpServletRequest request) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未登录或该账号没有权限");
    }
 
 
    @ExceptionHandler(CommonException.class)
    public ResponseEntity handleCommonException(CommonException e,
                                                HttpServletRequest request) {
        return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.SERVER_ERROR, e.getMessage()));
    }
 
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity handleRuntimeException(RuntimeException e,
                                                 HttpServletRequest request) {
        e.printStackTrace();
        logger.error("系统内部错误", e);
        return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.SERVER_ERROR, e.getMessage()));
    }
 
}