• spring @ExceptionHandler注解方式实现异常统一处理


       首先,在我们的工程中新建BaseController父类,内容如下:

    package com.ztesoft.zsmartcity.framework.exception;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.Date;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.log4j.Logger;
    import org.springframework.web.bind.annotation.ExceptionHandler;

    /**
    * 2015-11-06
    *
    * @author djw 统一异常处理,所有controler继承此类
    */
    public abstract class BaseController {
    @ExceptionHandler
    public String handleException(HttpServletRequest request,
    HttpServletResponse response, Exception e) {

    printException(e);// log4j打印错误级别堆栈日志信息,时间
    // json格式的ajax请求
    if (request.getHeader("accept").indexOf("application/json") > -1
    || (request.getHeader("X-Requested-With") != null && request
    .getHeader("X-Requested-With")
    .indexOf("XMLHttpRequest") > -1)) {
    response.setStatus(500);
    response.setContentType("application/json;charset=utf-8");
    try {
    PrintWriter writer = response.getWriter();
    if (e instanceof RuntimeException) {// 运行时异常
    writer.write("系统内部异常!");
    } else {// 非运行时异常
    writer.write(e.getMessage());// 此处待细化异常处理给提示 ???
    }
    writer.flush();
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    return null;
    } else {// URL普通请求
    if (e instanceof RuntimeException) {// 运行时异常
    request.setAttribute("exceptionMessage", "系统内部异常!");
    } else {
    request.setAttribute("exceptionMessage", e.getMessage());// 此处待细化异常处理给显示 ???
    }
    try {// 跳转统一异常处理界面
    request.getRequestDispatcher("../error.jsp").forward(
    request, response);
    } catch (ServletException | IOException e1) {
    e1.printStackTrace();
    }
    return null;
    }
    }

    public void printException(Exception e) {
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
    sw = new StringWriter();
    pw = new PrintWriter(sw);
    // 将出错的栈信息输出到printWriter中
    e.printStackTrace(pw);
    pw.flush();
    sw.flush();
    } finally {
    if (sw != null) {
    try {
    sw.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    if (pw != null) {
    pw.close();
    }
    }
    Logger.getLogger(BaseController.class).error(
    new Date() + ":" + sw.toString());
    }

    }

    所有controler类继承此类实现异常统一处理;

  • 相关阅读:
    关于HDFS默认block块大小
    从计算框架MapReduce看Hadoop1.0和2.0的区别
    Linux的作业管理
    php 随机密码和盐 来自wordpress
    SSH管理(重启 停止 运行 安装)centos7
    卸载iptables 小心了!!怎么关闭和卸载iptables
    mysqld: Out of memory 解决办法(mysql)
    ie6 ie7 ie8 ie9兼容问题终极解决方案
    call_user_func()的参数不能为引用传递 自定义替代方法
    centos 域名硬解析(linux)
  • 原文地址:https://www.cnblogs.com/jianwei-dai/p/4942756.html
Copyright © 2020-2023  润新知