ApiExceptionConfig.java 1.96 KB
Newer Older
吴泽佳's avatar
吴泽佳 committed
1 2
package com.tanpu.feo.feojob.config;

3
import com.tanpu.common.api.CommonResp;
吴泽佳's avatar
吴泽佳 committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class ApiExceptionConfig {
    /**
     * 捕捉全局所有的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
26
    public CommonResp<String> errorHandler(Exception e) {
钱坤's avatar
钱坤 committed
27
        log.error("==========全局异常: {}", e.getMessage(), e);
28
        return CommonResp.failed(e.getMessage());
吴泽佳's avatar
吴泽佳 committed
29 30 31 32 33 34 35 36 37
    }

    /**
     * 仅仅捕捉校验所产生的异常
     * @param exception
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
38
    public CommonResp<String> errorHandler(MethodArgumentNotValidException exception) {
吴泽佳's avatar
吴泽佳 committed
39 40 41 42 43 44 45 46 47 48 49 50 51
        StringBuilder errorInfo = new StringBuilder();
        BindingResult bindingResult=null;
        if(exception instanceof MethodArgumentNotValidException){
            bindingResult= ((MethodArgumentNotValidException)exception).getBindingResult();
        }
        for(int i = 0; i < bindingResult.getFieldErrors().size(); i++){
            if(i > 0){
                errorInfo.append(",");
            }
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
        }
        log.error("==========数据校验异常: {}", errorInfo.toString());
52
        return CommonResp.failed(errorInfo.toString());
吴泽佳's avatar
吴泽佳 committed
53 54
    }
}