package cn.com.countrygarden.bi.main.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.NoHandlerFoundException;

public class WebMvcHandlerExceptionResolver implements HandlerExceptionResolver {

    protected final Logger logger = LoggerFactory.getLogger(WebMvcHandlerExceptionResolver.class);

    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object object, Exception e) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMsg", "NOK");
            if (e instanceof ServiceException) {
                map.put("errorMsg", e.getMessage());
            } else if (e instanceof NoHandlerFoundException) {
                map.put("errorMsg", "接口 [" + request.getRequestURI() + "] 不存在");
            } else if (e instanceof ServletException) {
                map.put("errorMsg", e.getMessage());
            } else if (e instanceof IOException) {
                map.put("errorMsg", e.getMessage());
                e.printStackTrace();
            } else {
                map.put("errorMsg", "系统异常：" + e.getMessage());
                logger.info("e.printStackTrace()");
                e.printStackTrace();
            }
            writer.write(JSON.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (IOException ioe) {
            logger.info("ioe.printStackTrace()");
            ioe.printStackTrace();
        }
        return new ModelAndView();
    }
}