package com.sptg.common.core.handler;

import com.netflix.hystrix.exception.HystrixTimeoutException;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * title: GlobalExceptionHandler
 * package: com.sptg.common.core.handler
 * description: 全局异常处理器
 *                  
 *                
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获404异常
     * @param e NoHandlerFoundException
     * @return ResultBean
     *                  
     *                       
     */
    @ResponseBody
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResultBean noHandlerFoundException(NoHandlerFoundException e){
        return new ResultBean<>(ResultEnum.NOT_FIND,e.getMessage());
    }

    /**
     * 捕获运行时异常
     * @param e RuntimeException
     * @return ResultBean
     *                  
     *                       
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultBean runtimeException(Exception e){
        log.error(e.getMessage(),e);
        return new ResultBean<>(ResultEnum.ERROR,e.getMessage());
    }

    /**
     * 功能描述: 捕获超时异常
     * @param e HystrixTimeoutException
     * @return ResultBean
     *                  
     * date:  2018/10/31 0:08
     */
    @ResponseBody
    @ExceptionHandler(value = HystrixTimeoutException.class)
    public ResultBean hystrixTimeoutException(HystrixTimeoutException e){
        log.error(e.getMessage(),e);
        return new ResultBean<>(ResultEnum.REQUEST_TIME_OUT);
    }

    /**
     * 非法数据异常状态码
     */
    private final static String ILLEGAL_ARGUMENT_CODE = "400";

    /**
     * 捕获非法参数异常
     * @param e 异常信息
     * @return ResultBean
     */
    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResultBean illegalArgumentException(IllegalArgumentException e){
        return new ResultBean(ILLEGAL_ARGUMENT_CODE,e.getMessage());
    }

}
