package com.ywt.mg.web.interceptors;

import com.ywt.mg.core.utils.serializers.JsonSerializer;
import com.ywt.mg.web.BaseResponse;
import com.ywt.mg.web.PageDataResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
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 javax.servlet.http.HttpServletRequest;

/**
 * @author daiyihua
 * @create 2019-03-18 11:31 AM
 * @desc 异常全局拦截
 **/
@ControllerAdvice
@ResponseBody
public class ExceptionIntercept {

    private static Logger logger = LoggerFactory.getLogger(ExceptionIntercept.class);

    /**
     * MethodArgumentNotValidException 异常处理，用于处理 validation 里面的验证
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        int code = BaseResponse.PARAMETER_ERROR;
        return dealExceptionCommon(request, ex,code, fieldError.getDefaultMessage());
    }

    /**
     * MethodArgumentNotValidException 异常处理，用于处理 validation 里面的验证
     */
    @ExceptionHandler(BindException.class)
    public BaseResponse handleMethodArgumentNotValidException(HttpServletRequest request, BindException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        int code = BaseResponse.PARAMETER_ERROR;
        return dealExceptionCommon(request, ex,code, fieldError.getDefaultMessage());
    }

    /**
     * Exception 异常处理
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResponse defaultExceptionHandler(HttpServletRequest request, Exception e){
        int code = BaseResponse.OTHER_ERROR;
        String info = "数据读取失败";
        return dealExceptionCommon(request, e,code, info);
    }

    private BaseResponse dealExceptionCommon(HttpServletRequest request, Throwable e,int code, String info){
        PageDataResponse<Object> dataResponse = new PageDataResponse<>();
        e.printStackTrace();
        // 生成返回结果
        logger.error("url: {}",request.getRequestURL());
        logger.error("params: {}", JsonSerializer.toJson(request.getParameterMap()));
        logger.error(e.getMessage(), e);
        return dataResponse.failed(code, info);
    }
}
