import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

/**
 *
 * Description: 异常信息打印(controller继承此类即可调用)
 *
 * @author: Byron Wang
 * @version: V1.0
 */
public class CommonController {

    /**
     * Description:获取子类调用处方法名字
     * @return 调用处方法名
     */
    public String getCurMethodName() {
        // 获取调用处方法的名称
        return Thread.currentThread().getStackTrace()[2].getMethodName();
    }

    public static final int ENGLISH = 0;
    public static final int CHINESE = 1;

    private static final int MSG_NUM = 5;
    private static final int NOTICE_INDEX = 0;
    private static final int HAPPEN_INDEX = 1;
    private static final int CATCH_INDEX = 2;
    private static final int MSGE_INDEX = 3;
    private static final int DATETIME_INDEX = 4;

    /**
     * Description: 获取异常日志信息(本方法不适用于单元测试中)
     *
     * @param exception
     * @param lang
     * @return
     */
    public static String getExceptionLogMsg(Exception exception, int lang) {
        String[] header = { "DEBUG MESSAGE:::", "exception happen: [",
                "exception catch : [", "\tmessage: [", "datetime: ",
                "异 常 提 示 信 息:::", "异常发生: [",
                "异常捕获: [", "\t异常信息: [", "日期时间: " };
        String lineTail = "]\n\t\t";
        int baseindex = lang * MSG_NUM;
        StackTraceElement[] stes = exception.getStackTrace();
        StackTraceElement happenTrace = stes[0];
        StackTraceElement catchTrace = stes[stes.length - 1];
        // 获取异常信息,若为空则返回异常名称
        String message = exception.getMessage();
        if (message == null || message.trim().length() == 0
                || "null".equalsIgnoreCase(message)) {
            message = exception.getClass().getName();
        }

        StringBuilder builder = new StringBuilder(header[baseindex + NOTICE_INDEX]);
        String nowStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        builder.append(header[baseindex + DATETIME_INDEX]).append(nowStr);
        builder.append(header[baseindex + MSGE_INDEX])
                .append(message).append(lineTail);
        builder.append(header[baseindex + HAPPEN_INDEX])
                .append(joinExceptionPosition(happenTrace));
        builder.append(header[baseindex + CATCH_INDEX])
                .append(joinExceptionPosition(catchTrace));
        return builder.toString();
    }

    /**
     * Description: 拼接异常位置
     *
     * @param element
     * @return
     *
     */
    private static String joinExceptionPosition(StackTraceElement element) {
        String lineTail = "]\n\t\t";
        String seprator = "..";
        StringBuilder builder = new StringBuilder();
        builder.append(element.getClassName()).append(seprator)
                .append(element.getMethodName()).append(seprator)
                .append(element.getLineNumber()).append(lineTail);
        return builder.toString();
    }

    /**
     * TEST
     *
     * @throws IOException
     */
    public static void getException() throws IOException {
        throw new IOException("解析参数出错");
    }

    public static void getException2() throws IOException {
        getException();
    }

    @Test
    public void testException() {
        try {
            getException2();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(getExceptionLogMsg(e, CHINESE));
        }
    }

    @Test
    public void testExceptionNoMsg() {
        try {
            throw new StringIndexOutOfBoundsException();
        } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
            System.out.println(getExceptionLogMsg(e, CHINESE));
        }
    }

    public static void main(String[] args) {
        try {
            throw new StringIndexOutOfBoundsException();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(getExceptionLogMsg(e, CHINESE));
        }
        // try {
        // getException2();
        // } catch (IOException e) {
        // e.printStackTrace();
        // System.out.println(getExceptionLogMsg(e, CHINESE));
        // }
    }

}

Java异常信息处理的更多相关文章

  1. Java异常错误的面试题及答案

    1) Java中什么是Exception? 这个问题经常在第一次问有关异常的时候或者是面试菜鸟的时候问.我从来没见过面高级或者资深工程师的 时候有人问这玩意,但是对于菜鸟,是很愿意问这个的.简单来说, ...

  2. java异常面试常见题目

    在Java核心知识的面试中,你总能碰到关于 处理Exception和Error的面试题.Exception处理是Java应用开发中一个非常重要的方面,也是编写强健而稳定的Java程序的关键,这自然使它 ...

  3. 浅谈java异常[Exception]

    学习Java的同学注意了!!! 学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:589809992 我们一起学Java! 一. 异常的定义 在<java编程思想 ...

  4. 基础知识《十》java 异常捕捉 ( try catch finally ) 你真的掌握了吗?

    本文转载自  java 异常捕捉 ( try catch finally ) 你真的掌握了吗? 前言:java 中的异常处理机制你真的理解了吗?掌握了吗?catch 体里遇到 return 是怎么处理 ...

  5. Java异常体系及分类

    上图是基本的java异常体系结构. 主要分为2大类:Error和Exception 1.Error:描述了Java运行系统中的内部错误以及资源耗尽的情形.应用程序不应该抛出这种类型的对象,一般是由虚拟 ...

  6. Java异常之自定义异常

    哎呀,妈呀,又出异常了!俗话说:"代码虐我千百遍,我待代码如初恋". 小Alan最近一直在忙着工作,已经很久没有写写东西来加深自己的理解了,今天来跟大家聊聊Java异常.Java异 ...

  7. 第11章 Java异常与异常处理

    1.Java异常简介 1.什么是异常异常出现的时候代码会无法正常运行下去,会产生各种问题2.捕捉异常的作用提早发现异常,方便查找问题,并给出解决方法3.Java中的异常1.Java中所有不正常的类都是 ...

  8. java 异常

    1.java异常 2.自定义抛出 3.运行时异常,程序有问题,让使用者可以改' ' 4.return  和  throw的区别 return 符合函数要求的值    throw  有问题的时候用它结束 ...

  9. 3.Java异常进阶

    3.JAVA异常进阶 1.Run函数中抛出的异常 1.run函数不会抛出异常 2.run函数的异常会交给UncaughtExceptionhandler处理 3.默认的UncaughtExceptio ...

随机推荐

  1. Configuring a Windows Azure Project

    A Windows Azure project includes two configuration files: ServiceDefinition.csdef and ServiceConfigu ...

  2. 从web页面启动winform程序的实现方法

    本文实现的需求是: A.通过web页面启动winform程序: B.将页面的参数传递给winform程序: C.winform程序已经启动并正在运行时,从web页面不能重新启动winform程序,只是 ...

  3. C#怎样处理xml文件的大于号和小于号等常用符号(xml符号引发的程序错误)

    在程序中由xml配置而成的sql语句要转换为C#支持的sql语句 <settings> <select> a.*</select> <from> (se ...

  4. 小白学Linux(五)--VI/VIM编辑器

    我们操作文件,终究离不开编辑文件,对文件内容的编辑,Linux系统下,我们通常使用VI/VIM来编辑文件.VI是每个Linux都会自带的文本编辑器,VIM是VI的增强版,可能有些发行版本没有自带,可以 ...

  5. [PHP] url的pathinfo模式加载不同控制器的实现

    使用自动加载和解析url的参数,实现调用到不同的控制器,实现了pathinfo模式和普通的url模式 文件结构: |--Controller |--Index |--Index.php |--Appl ...

  6. Eclipse 出现Some sites could not be found. See the error log for more detail.错误 解决方法

    Eclipse 出现Some sites could not be found.  See the error log for more detail.错误 解决方法 Some sites could ...

  7. 【GOF23设计模式】策略模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_策略模式.CRM中报价策略.GUI编程中布局管理器底层架构 package com.test.strategy; /** ...

  8. swift学习笔记之-函数

    //函数 import UIKit /*获得系统时间 var date = NSDate() var timeFormatter = NSDateFormatter() timeFormatter.d ...

  9. javascript数组浅谈1

    最近心血来潮要开始玩博客了,刚好也在看数组这块内容,第一篇就只好拿数组开刀了,自己总结的,有什么不对的地方还请批评指正,还有什么没写到的方面也可以提出来我进行完善,谢谢~~ 首先,大概说说数组的基本用 ...

  10. Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39

    Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39 V1  初步实现sina csdn cnblogs V2  实现qzone sohu 的发帖 ...