package com.yingying.tourist.exception;

import com.yingying.tourist.common.Util;
import com.yingying.tourist.result.MessageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestBindingException;
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;
import java.util.Map;
import java.util.Set;

/**
 * @Author: XPF
 * @Description:
 * @Date: Created in 13:43 2018/7/3
 * @Modified by:
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    //声明要捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public MessageResult defultGlobalExcepitonHandler(HttpServletRequest request, Exception e) {
        logger.error("请求地址："+request.getRequestURL());
        String param = "{ ";
        Map<String,String[]> enu = request.getParameterMap();
        Set<Map.Entry<String, String[]>> set = enu.entrySet();
        for (Map.Entry<String, String[]> entry : set){
            String[] para= enu.get(entry.getKey());
            String paraName = "";
            if (Util.isNotNull(para) && para.length>0){
                for (String a : para) {
                    paraName += a+";";
                }
            }
            param += entry.getKey()+": "+paraName;
        }
        logger.error("请求参数："+param.substring(0, param.length()-1)+" }");
        logger.error(e.getMessage(), e);
        if (e instanceof SessionTimeoutException) {
            return  new MessageResult().failure(ErrorCode.SESSION_TIMEOUT);
        } else if (e instanceof ParameterException) {
            return new MessageResult().failure(ErrorCode.PARAMETERS_ERROR);
        } else if (e instanceof ServerBizException) {
            return new MessageResult().failure(ErrorCode.SERVER_BIZERR);
        } else if (e instanceof IllegalArgumentException) {
            return new MessageResult().failure(ErrorCode.PARAMETERS_ERROR);
        } else if (e instanceof ServletRequestBindingException) {
            return new MessageResult().failure(ErrorCode.PARAM_BINDINGERR);
        }
        return new MessageResult().failure(ErrorCode.SERVER_SYSERR);
    }
}
