mitao
2024-06-06 3d2b51ea4520533de5e78f88dddf5b5c7dce4247
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
package com.sinata.rest.common.aop;
 
import com.sinata.rest.common.ApiUtils;
import com.sinata.rest.common.exception.BizExceptionEnum;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
 
import javax.validation.ConstraintViolationException;
 
/**
 * 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends BaseControllerExceptionHandler {
 
    /**
     * 拦截jwt相关异常
     */
    @ExceptionHandler(JwtException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object jwtException(JwtException e) {
        return ApiUtils.returnNG(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
    }
 
    /**
     * 参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({IllegalArgumentException.class, ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object resultParamError(Exception e) {
        StackTraceElement stackTraceElement = e.getStackTrace()[1];
        log.error("运行异常:{},{},{},{}", stackTraceElement.getFileName(), stackTraceElement.getMethodName(), stackTraceElement.getLineNumber(), e.getMessage());
        return ApiUtils.returnNG(e.getMessage());
    }
}