package com.manage.controller;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2020/5/15 16:14
 * @UpdateUser: 曾文和
 * @UpdateDate: 2020/5/15 16:14
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.manage.util.ExceptionPrintUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)//指定拦截的异常
    public ModelAndView errorHandler(Exception e) {
        return returnMv(e, "服务器出错了,请联系系统管理员");
    }

    @ExceptionHandler(value = RuntimeException.class)//指定拦截的异常
    public ModelAndView runtimeHandler(Exception e) {
        return returnMv(e, "服务器出错了,请联系系统管理员");
    }

    private ModelAndView returnMv(Exception e, String msg) {
        ModelAndView mv = new ModelAndView();
        /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<>(1);
        attributes.put("code", "500");
        attributes.put("msg", msg);
        view.setAttributesMap(attributes);
        mv.setView(view);
        ExceptionPrintUtil.printException(e);
        e.printStackTrace();
        return mv;
    }
}
