package com.dgtly.apiframework.exception;

import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ResultType;
import com.dgtly.common.exception.api.ApiTokenTimeoutException;
import com.dgtly.common.exception.api.LessParamException;
import com.dgtly.common.exception.api.NoLoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 
 * @author dgtly
 */
@RestControllerAdvice
public class ApiGlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(ApiGlobalExceptionHandler.class);


    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }
    /**
     * 缺少参数
     */
    @ExceptionHandler(LessParamException.class)
    public AjaxResult handleException(LessParamException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(ResultType.LESSPARAM,e.getMessage());
    }
    /**
     * 未登录
     */
    @ExceptionHandler(NoLoginException.class)
    public AjaxResult handleException(NoLoginException e)
    {
        return AjaxResult.error(ResultType.NOLOGIN);
    }
    /**
     * token超时
     */
    @ExceptionHandler(ApiTokenTimeoutException.class)
    public AjaxResult handleException(ApiTokenTimeoutException e)
    {
        return AjaxResult.error(ResultType.TOKENTIMEOUT);
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e)
    {
        log.error("运行时异常:", e);
        return AjaxResult.error("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error("服务器错误，请联系管理员");
    }

}
