Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to process/handle Error stream messages

I need to process different Error/Exception messages generated compile/run time.

I execute a Java program an read the stream thus generated :

final Process p2 = builder.start();
BufferedReader in = new BufferedReader(new                                                 
        InputStreamReader(p2.getInputStream()));

For each success , the output is generated and shown. No problem there. But I need to show custom message for every Error message.

EG:

Error: Main method not found in class dummy.helloParse10.hello, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

May be customized as : Error: Main method not found

My current approach is very ugly and limited . I am looking if "Exception" string is present in error stream and then taking out the sub- strings.Something like :

if(tError.contains("Exception"))            
      tError=tError.substring(tError.indexOf("main\"")+5,tError.indexOf("at"))
        + "( At Line: "+tError.substring(tError.indexOf(".java")+6);

But it do not customize my approach in a broad way.

What is the best thing I could do?

Edit :

I think my question is unclear. Basically I am executing a Java program via ProcessBuilder.

    //Compile the program 
  Process p = Runtime.getRuntime().exec("javac filename ");

    // Now get the error stream if available :
  BufferedReader in = new BufferedReader(new            
                    InputStreamReader(p.getOutputStream()));

 String line = null;
 while ((line = in.readLine()) != null) {

       //process error in compilation.
       }
    ...
    ...
  // ProcessBuilder to execute the program.java
  //Read the output or runtime Exception  

No the output of the process can be the result of te java program or an exception/error which is taken from the process steam an is in String form.Need to manipulate those Errors.

Update :

I can now solve the compile time errors via Java Compiler API as suggested by @Miserable Variable .How can I deal with Runtime Exceptions similarly ?

EDIT : In actual it is not possible to modify the program to be run in a new process.They are user specific.

like image 843
joey rohan Avatar asked Dec 19 '22 22:12

joey rohan


1 Answers

For identifying errors in compilation, instead of running javac using ProcessBuilder a better alternative might be to use Java Compiler API.

I have never used it myself but it seems pretty straightforward.

like image 134
Miserable Variable Avatar answered Dec 21 '22 11:12

Miserable Variable