springmvc全局的异常处理

添加bean

<!-- 统一处理异常 -->
    <bean id="exceptionHandler" class="com.ak1ak1.common.shiro.ExceptionHandler"/>

Java代码

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ak1ak1.utils.AjaxResult;
import com.alibaba.fastjson.JSON;

/**
 * 
 * @author hejie
 * @date 2019年9月18日
 * @desc 统一处理异常
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error(ex.getMessage(), ex);
        // 如未捕获异常,统一返回系统错误异常
        return outJson(request, response, AjaxResult.error("系统异常,请联系管理员!"));
    }

    private ModelAndView outJson(HttpServletRequest request, HttpServletResponse response, AjaxResult ajax) {
        ModelAndView mv = new ModelAndView();
        /*  使用response返回    */
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            response.getWriter().write(JSON.toJSONString(ajax));
        } catch (IOException e) {
            logger.error("与客户端通讯异常:" + e.getMessage(), e);
        }
        return mv;
    }
}

 

posted @ 2019-09-19 14:45  明年上初中  阅读(179)  评论(0编辑  收藏  举报