package cn.superdesk.uniorder.openapi.config.exception;

import cn.superdesk.uniorder.common.exception.OpenApiException;
import cn.superdesk.uniorder.openapi.api.base.O;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
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 xc
 * @description
 * @date 2022/3/24 15:09
 */
@ControllerAdvice
@Slf4j
public class OpenApiExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public O exceptionHandler(Exception e, HttpServletRequest request) {
        O o = new O();
        //接口
        String requestURL = request.getRequestURL().toString();

        if (e instanceof OpenApiException) {
            OpenApiException e1 = (OpenApiException) e;
            o.setResultCode(e1.getCode());
            o.setResultMessage(e1.getMessage());
            o.setSuccess(false);
        } else {
            o.setResultCode(500);
            //o.setResultMessage("同步失败");
            o.setResultMessage(e.getLocalizedMessage());
            o.setSuccess(false);
        }
        log.error("接口调用失败,接口地址信息:{}, \n错误信息:",requestURL,e);
        return o;
    }


    /**
     * 方法参数校验异常处理
     */
    @ExceptionHandler(ParameterNotValidException.class)
    @ResponseBody
    public O handleMethodArgumentNotValidException(ParameterNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String field = fieldError.getField();
        String defaultMessage = fieldError.getDefaultMessage();
        O o = new O();
        o.setResultCode(500);
        o.setSuccess(false);
        o.setResultMessage(field + ":" +defaultMessage);
        return o;
    }
}
