Exception information capture and output

Business exceptions need to send file alarms, but it is very troublesome to look through the logs every time to locate the problem, but it is much more convenient to capture the specific cause of the exception and the detailed error lines~


Packaging method:

public static String getErrorInfoFromException(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String errorMessage = sw.toString();
            char [] errorMessages = sw.toString().toCharArray();
            //获取异常头部信息
            StringBuffer outErrorMessage = new StringBuffer();
            outErrorMessage.append("\n异常类型:" + e.getMessage());
            //获取异常输出各个()下标
            //这里初始化10个只取前10个类信息用来定位问题,一般也够用了,定位不到的修改初始长度
            int initsize = 10;
            ArrayList<Integer> leftIndex = new ArrayList();
            ArrayList<Integer> rightIndex = new ArrayList();
            for (int i=0;i<errorMessages.length;i++){
                if(errorMessages[i]=='('){
                    leftIndex.add(i);
                }else if(errorMessages[i]==')'){
                    rightIndex.add(i);
                }
                if (rightIndex.size() == initsize) {
                    break;
                }
            }
            outErrorMessage.append("\n异常详细地址:");
            for(int i=0;i<leftIndex.size();i++){
                outErrorMessage.append(errorMessage.substring(leftIndex.get(i)+1,rightIndex.get(i))+"\n");
            }
            return outErrorMessage.toString();
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";
        }
    }

 

Test case:

public static void main(String[] args) {
        ArrayList list=null;
        try {
            System.out.println(list.get(5));
        }catch (Exception e){
            String errorInfoFromException = SendMsg.getErrorInfoFromException(e);
            System.out.println(errorInfoFromException);
        }

    }

Print information:

 

Of course, there are some performance problems with cyclic characters here, so I'm too lazy to optimize.

If you have a better way, leave a message and let me learn.

If the article is helpful to you, give me a thumbs up!

Guess you like

Origin blog.csdn.net/luxiangyan1923/article/details/115699527