Java Exception captures and displays instance details

  • 2020-06-15 09:08:39
  • OfStack

Java Exception captures and displays instance details

When developing the Java B/S architecture, it is often the case that the back end handles the business logic and the front end is responsible for the presentation. When the back end handles the exception, how do you present the error message to the front end? Error message stack is usually a lot of, it is more convenient for developers to find problems, but for customers, dozen 1 heap of error messages, is undoubtedly a kind of damage to their senses, how to capture the most important information to display to the client? The message should be concise, point to the error point, and indicate the type of exception.

In many cases, the getMessage() method of Exception returns an empty value that would appear in the front end if used this way. There are two important pieces of information we want to display:

Exception types Error points and error messages

1. How to get the exception type?

This can be achieved through the getClass().getName () method of Exception.

2. How to get the error point?

Error point message 1 normally marks the beginning line of "Cause by:". If the row can be captured, the exception information can be retrieved. An example of an exception stack is as follows:


Caused by: org.apache.activemq.selector.ParseException: Parse error at line 0, column 0. Encountered: <EOF> 
  at org.apache.activemq.selector.SelectorParser.generateParseException(SelectorParser.java:1231) 
  at org.apache.activemq.selector.SelectorParser.jj_consume_token(SelectorParser.java:1179) 
  at org.apache.activemq.selector.SelectorParser.unaryExpr(SelectorParser.java:468) 
  at org.apache.activemq.selector.SelectorParser.multExpr(SelectorParser.java:390) 
  at org.apache.activemq.selector.SelectorParser.addExpression(SelectorParser.java:359) 
  at org.apache.activemq.selector.SelectorParser.comparisonExpression(SelectorParser.java:211) 
  at org.apache.activemq.selector.SelectorParser.equalityExpression(SelectorParser.java:156) 
  at org.apache.activemq.selector.SelectorParser.andExpression(SelectorParser.java:135) 
  at org.apache.activemq.selector.SelectorParser.orExpression(SelectorParser.java:114) 
  at org.apache.activemq.selector.SelectorParser.JmsSelector(SelectorParser.java:106) 
  at org.apache.activemq.selector.SelectorParser.parse(SelectorParser.java:84) 
  ... 63 more 

For some reason, it usually does not appear in line 1, so the error point and error message cannot be obtained by fetching line 1.

If you parse the output yourself and read it line by line, you can also grab the error point and error message by determining whether the first character is "Caused by:".

The simplest approach, again using regular expressions, makes it relatively easy to capture error points and error messages. Such as:

Code 1: Use regular expressions to get error points and error messages


String regEx = "Caused by:(.*)";  
Pattern pat = Pattern.compile(regEx);  
Matcher mat = pat.matcher(content);  
boolean rs = mat.find();  
System.out.println("found?" + rs); 
System.out.println(mat.group(1)); 

The result output of code 1:


org.apache.activemq.selector.ParseException: Parse error at line 0, column 0. Encountered: <EOF>

3. Acquisition of exception information

You know how to find the error point, but how to get the exception information? Although there are error point messages in ES55en.printStrackTrace (), they are all called on the console, Exception.getStackTrace (), and the prompt message of the error point cannot be obtained.

One solution is to capture the output of ES62en.printStrackTrace (). Using the method e.printStackTrace (PrintStream), output the exception stack information to ByteOutputStream first, and then convert ByteOutputStream to a string to get the complete output of the exception. The code is:

Code 2: Get the full exception information


ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
e.printStackTrace(new PrintStream(baos)); 
String exception = baos.toString(); 
System.out.println("baos:" + exception); 

Complete test code -- exception Caused by catch (note: the word Caused by does not appear in this test code, but there are many actual application codes, which are not included in the test case):


import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.PrintStream; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 
public class RegexpTest { 
  /** 
   *  Read the contents of the file  
   * @return 
   */ 
  public String readFile(){ 
    try { 
      String fileName = "D:\\test2\\exception.log"; 
      File f = new File(fileName); 
      FileInputStream fis = new FileInputStream(f); 
      int filesize = fis.available(); 
      byte[] buffer = new byte[filesize]; 
      fis.read(buffer); 
      return new String(buffer); 
    } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
    }     
  } 
   
  /** 
   *  Regular expression test  
   */ 
  public void test(){ 
    try { 
      String content = readFile(); 
      System.out.println(content); 
       
      String regEx = "Caused by:(.*)";  
      Pattern pat = Pattern.compile(regEx);  
      Matcher mat = pat.matcher(content);  
      boolean rs = mat.find();  
      System.out.println("found?" + rs); 
      System.out.println(mat.group(1)); 
//     for(int i=1;i<=mat.groupCount();i++){  
//       System.out.println("found:" + mat.group(i));  
//     }   
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
   
  public void test2(){ 
    try { 
      FileInputStream fis = new FileInputStream("d:\\test.txt"); 
      fis.read(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      e.printStackTrace(new PrintStream(baos)); 
      String exception = baos.toString(); 
      System.out.println("exception:" + exception); 
    } 
  } 
   
  public static void main(String[] args) { 
    RegexpTest rt = new RegexpTest(); 
    //rt.test(); 
    rt.test2(); 
  } 

4, there is also a simple way to get exception types and error points

Get the error point type:


e.getCause().getClass() 

Get error point information (error cause) :


e.getCause().getMessage() 

Code sample (note: actual code interception, not directly run) :


 @SuppressWarnings("unchecked") 
  @RequestMapping(value="/createSubscriber", method = RequestMethod.POST) 
  public @ResponseBody 
  WrappedResult createSubscriber(@ItemsRequestBody List<Map> list) { 
    LocalBrokerFacade facade = new LocalBrokerFacade(BrokerRegistry.getInstance().findFirst()); 
    WrappedResult result = new WrappedResult(); 
    try { 
      Map params = list.get(0); 
      String clientId = (String)params.get("clientId"); 
      String subscriberName = (String)params.get("subscriberName"); 
      String topicName = (String)params.get("topicName"); 
      String selector = (String)params.get("selector"); 
       
//     if("".equals(selector)){ 
//       selector = null; 
//     } 
       
      facade.getBrokerAdmin().createDurableSubscriber(clientId, 
          subscriberName,topicName,selector); 
      result.setSuccessful(true); 
    } catch (Exception e) { 
      System.out.println("Exception:" + e.getCause().getClass() + "," + e.getCause().getMessage()); 
      //log.error("createSubscriber failed.", e); 
    } 



Output:


Exception:class org.apache.activemq.selector.ParseException,Parse error at line 0, column 0. Encountered: <EOF>

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: