Springmvc自定义统一异常处理

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1.默认异常处理(不友好)

Springmvc自定义统一异常处理_第1张图片

 

2.自定义统一异常处理流程

1)demo-base中pom.xml修改


    javax.servlet
    javax.servlet-api
    3.1.0
    provided

2)自定义异常处理类-DemoExceptionResolver

在demo-base中定义DemoExceptionResolver,实现HandlerExceptionResolver接口即可

package com.demo.base.Exception;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class DemoExceptionResolver implements HandlerExceptionResolver {
    private static final Logger LOG = LoggerFactory.getLogger(DemoExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            LOG.error(e.getMessage(),e);
        }

        if (ex instanceof DemoException) {
            pw.write(ex.getMessage());
        } else {
            pw.write("系统异常,请联系管理员");
        }

        return new ModelAndView();
    }
}

3)DemoExceptionResolver注入到Spring容器中

在demo-web中spring-mvc.xml配置:

4)运行测试结果

Springmvc自定义统一异常处理_第2张图片

3.参考文章

http://www.voidcn.com/blog/eson_15/article/p-6069524.html

转载于:https://my.oschina.net/u/2526015/blog/748122

你可能感兴趣的:(Springmvc自定义统一异常处理)