package com.fufan.mtsaas.exception;

import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.terracotta.offheapstore.paging.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @Resource
    private HttpServletRequest request;

    private String getTraceId(){
        return request.getHeader("traceId");
    }

    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        Result result = new Result<>();
        result.setResStatus(ResStatus.STATUS_WRONGFUL);
        result.setResMsg(objectError.getDefaultMessage());
        return result;
    }



    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Result handlerException(RuntimeException e) {
        log.error(e.getMessage());
        log.error(Arrays.toString(e.getStackTrace()));
        e.printStackTrace();
        Result result = new Result<>();
        result.setResStatus(ResStatus.STATUS_FAILED);
        result.setResMsg(e.getMessage());
        // 处理通用异常
        return result;
    }

}
