package com.elephant.framework.galaxy.aroad.module.common.controller;

import com.elephant.framework.galaxy.aroad.exception.GlobalException;
import com.elephant.framework.galaxy.aroad.exception.GlobalExceptionEnum;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @auther wangjian
 * @create 2019-02-18 16:07
 */
@Slf4j
public class BaseController {

    /**
     * 解决所有未被Controller层处理的异常，不会反应的客户端
     *
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception exception) {
        exception.printStackTrace();
        if (exception instanceof GlobalException) {
            GlobalException globalException = (GlobalException) exception;
            return new R(globalException.getErrorCode(),globalException.getErrorMessage());
        } else if (exception instanceof AccessDeniedException) {
            AccessDeniedException accessDeniedException = (AccessDeniedException) exception;
            return new R(accessDeniedException);
        } else {
            return new R(GlobalExceptionEnum.UNKNOWN_ERROR.getErrorCode(), GlobalExceptionEnum.UNKNOWN_ERROR.getErrorMessage());
        }
    }

}
