package com.loan.system.exception;

import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;

/**
 *  统一异常处理
 * @author EdwinXu
 * @date 2020/9/2 - 20:28
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result exceptionGet(Exception e) {
        if (e instanceof DescribeException) {
            DescribeException myException = (DescribeException) e;
            logger.error("[ 异常 >> "+e.toString()+" ]");
            return ResultUtil.error(myException.getCode(), myException.getMessage());
        } else if(e instanceof FileException){
            FileException myException = (FileException) e;
            logger.error("[ 异常 >> "+e.toString()+" ]");
            return ResultUtil.error(myException.getCode(), myException.getMessage());
        } else if (e instanceof AccessDeniedException){
            logger.error("[ 异常 >> "+e.toString()+" ]");
            return ResultUtil.error(ExceptionEnum.PERMISSION_DENIED);
        } else if (e.toString().split("\\.")[e.toString().split("\\.").length - 1].equals(
                ExceptionEnum.NullPointerException.name())) {
            logger.error("[ 异常 >>  ]", e);
            return ResultUtil.error(ExceptionEnum.NullPointerException);
        } else {
            logger.error("[ 异常 >>  ]", e);
            return ResultUtil.error(ExceptionEnum.UNKNOWN_ERROR);
        }
    }
}
