liurunyu
2024-06-11 914bc07f2ff447f916b736da84d766cda8c6f67b
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
package com.dy.pmsGlobal.aop;
 
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.BaseResponseUtils;
import lombok.extern.slf4j.Slf4j;
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;
 
@ResponseBody
@RestControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {
 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        log.error("[handleValidationExceptions]", ex);
        StringBuilder sb = new StringBuilder();
        ex.getBindingResult().getAllErrors().forEach(error -> {
//            String fieldName = ((org.springframework.validation.FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            sb.append(errorMessage).append(";");
        });
        return BaseResponseUtils.buildException(sb.substring(0, sb.length() - 1));
    }
    /**
     * 处理系统异常,兜底处理所有异常
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<?> defaultExceptionHandler(Throwable ex) {
        log.error("[defaultExceptionHandler]", ex);
        // 返回 ERROR
        return BaseResponseUtils.buildException(ex.getMessage());
    }
 
}