package com.izouma.awesomeadmin.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        if (e instanceof UnauthorizedException) {
            mav.addObject("error", "无权限");
            mav.addObject("code", 10002);
        } else if (e instanceof UnauthenticatedException) {
            mav.addObject("error", "未登录");
            mav.addObject("code", 10001);
        } else if (e instanceof AuthenticationException) {
            mav.addObject("error", e.getMessage());
            mav.addObject("code", 10001);
        } else {
            mav.addObject("error", e.getMessage());
            e.printStackTrace();
        }
        mav.addObject("success", false);
        return mav;
    }
}
