package com.pannk.mms.common.exception;

import com.pannk.mms.common.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created by wolf on 20-11-3.
 */
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    /**
     * 处理自定义异常
     * @param e 自定义异常
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException e){
        Result result = new Result();
        result.put("code",e.getCode());
        result.put("msg",e.getMsg());
        return result;
    }

    /**
     * handler不存在异常
     * @param e 路径不存在
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNoHandlerFoundException(NoHandlerFoundException e){
        log.error("访问路径不存在,{}",e);
        return Result.error(404,"访问路径不存在");
    }

    /**
     * 记录重复异常
     * @param e 数据库已存在记录
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("数据库中已存在记录");
        return Result.error("数据库中已存在记录");
    }

    /**
     * 无权限
     * @param e 无权限
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public Result handleAuthorizationException(AuthorizationException e){
        log.error("没有相关权限,{}",e);
        return Result.error(401,"没有权限,请联系管理员");
    }
}
