SoFunction
Updated on 2025-03-08

Java Exception capture and display instance detailed explanation

Java Exception capture and display instance detailed explanation

When developing Java B/S architecture, there are often scenarios: the backend handles business logic, and the frontend is responsible for displaying it. When an exception occurs in the backend processing, how to display the error information to the frontend? There are usually many error information stacks, which are more convenient for developers to find problems, but for customers, tying a bunch of error information is undoubtedly a destruction of their senses. How to capture the most important information and display it to the client? This information requires conciseness, pointing to the error point, and indicating the type of exception.

In many cases, the getMessage() method of Exception returns an empty value, and if this method is used, it will display an empty value on the front end. There are two important information we want to display:

  • Exception type
  • Error points and error information

1. How to obtain exception types?

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

2. How to obtain error points?

The error point information is usually in the line that starts with "Cause by:". If this line can be captured, exception information can be retrieved. An exception stack example is as follows:

Caused by: : Parse error at line 0, column 0. Encountered: <EOF> 
  at (:1231) 
  at .jj_consume_token(:1179) 
  at (:468) 
  at (:390) 
  at (:359) 
  at (:211) 
  at (:156) 
  at (:135) 
  at (:114) 
  at (:106) 
  at (:84) 
  ... 63 more 

For some reasons, it often does not appear in the first line, so the error point and error prompt information cannot be obtained by taking the first line.

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

The easiest way is to use regular expressions, which can be used to capture error points and error information relatively simply. For example:

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

String regEx = "Caused by:(.*)";  
Pattern pat = (regEx);  
Matcher mat = (content);  
boolean rs = ();  
("found?" + rs); 
((1)); 

The result output of code 1:

: Parse error at line 0, column 0. Encountered: <EOF>

3. Obtaining exception information

Although I know how to find the error point, how to obtain exception information? Although there is error point information in (), it is all called to the console. (), and the error point prompt information cannot be obtained.

A solution is to capture the () output. Use the (PrintStream) method to output the exception stack information to ByteOutputStream first, and then convert ByteOutputStream to a string to obtain the complete output of the exception. The code is:

Code 2: Get the complete exception information

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
(new PrintStream(baos)); 
String exception = (); 
("baos:" + exception); 

Complete test code - Exception Caused by capture (Note: The word Caused by does not appear in the test code, there are many actual application codes and are not put into the test cases):

import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
public class RegexpTest { 
  /**
    * Read content in the file
    * @return
    */ 
  public String readFile(){ 
    try { 
      String fileName = "D:\\test2\\"; 
      File f = new File(fileName); 
      FileInputStream fis = new FileInputStream(f); 
      int filesize = (); 
      byte[] buffer = new byte[filesize]; 
      (buffer); 
      return new String(buffer); 
    } catch (Exception e) { 
      (); 
      return null; 
    }     
  } 
   
  /**
    * Regular expression test
    */ 
  public void test(){ 
    try { 
      String content = readFile(); 
      (content); 
       
      String regEx = "Caused by:(.*)";  
      Pattern pat = (regEx);  
      Matcher mat = (content);  
      boolean rs = ();  
      ("found?" + rs); 
      ((1)); 
//     for(int i=1;i&lt;=();i++){  
//       ("found:" + (i));  
//     }   
    } catch (Exception e) { 
      (); 
    } 
  } 
   
  public void test2(){ 
    try { 
      FileInputStream fis = new FileInputStream("d:\\"); 
      (); 
    } catch (Exception e) { 
      (); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      (new PrintStream(baos)); 
      String exception = (); 
      ("exception:" + exception); 
    } 
  } 
   
  public static void main(String[] args) { 
    RegexpTest rt = new RegexpTest(); 
    //(); 
    rt.test2(); 
  } 

4. There is another simple way to get exception types and error points.

Get the error point type:

().getClass() 

Get the error point information (the reason for the error):

().getMessage() 

Code example (Note: actual code intercepts, cannot be run directly):

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



Output:

Exception:class ,Parse error at line 0, column 0. Encountered: <EOF>

Thank you for reading, I hope it can help you. Thank you for your support for this site!