fangyuan
2022-11-17 059eebfe1c54750e74e290ed7503e2cbf3f2f740
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.ycl.config;
 
import com.ycl.api.CommonResult;
import com.ycl.enums.common.ResultCode;
import com.ycl.exception.ApiException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletRequest;
 
@Configuration
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class ExceptionConfiguration {
    // 捕获自定义异常数据
    @ExceptionHandler(value = ApiException.class)
    public CommonResult HandlePubException(ApiException pubExceptions) {
        if (pubExceptions.getErrorCode() != null) {
            System.out.println(String.format("错误:%d: %s",
                    pubExceptions.getErrorCode().getCode(),
                    pubExceptions.getErrorCode().getMessage()));
        }
        return CommonResult.failed(pubExceptions.getMessage());
    }
 
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult HandleParamsException(HttpServletRequest request, MethodArgumentNotValidException exception) {
        StringBuffer buffer = new StringBuffer();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            buffer.append(String.format("参数:%s,值为:%s, 原因:%s。", error.getField(), error.getRejectedValue(), error.getDefaultMessage()));
        }
        return CommonResult.failed(ResultCode.VALIDATE_FAILED, buffer.toString());
    }
 
    // 捕获其他异常
    @ExceptionHandler// 直接返回500
    public CommonResult HandleAllException(Exception exception) {
 
 
        exception.printStackTrace();
        // todo 记录日志
 
        return CommonResult.failed(ResultCode.FAILED, "系统错误");
    }
 
}