0

I need to store an error message in a string after the error has occurred. I am unable to use the try and catch blocks as the error will appear after the initial code is run.

Before I was using the code below to store the error message in a file when it appeared:

PrintStream printS = new PrintStream("file.txt");  
System.setErr(pst);

However I want to store it and a string and send this string else where after the error occured. I have tried already using a byte array output stream:

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
PrintStream printS = new PrintStream(byteArray);  
System.setErr(pst);
String tester = byteArray.toString(StandardCharsets.UTF_8);

But when I try to print the string it is empty and does not contain the error. Does anyone know how I can run code after a error has occurred, so I can send this error message elsewhere?

1 Answers1

0

Java just runs code on the spot, you're not defining triggers for the future. You are creating a new empty byte array output stream, setting it up as 'target' for any System.err calls later, and then immediately turning it into a string. It's still blank at this point, of course.

What you want is quite complicated - you'd have to write a custom PrintStream that saves anything sent to it, until it 'sees' a newline and then acts. Something like:

OutputStream myCustomReportingStream = new OutputStream() {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();

  @Override public void write(int b) {
    if (b == '\r') continue;
    if (b == '\n') {
      process(new String(buffer.getBytes(), StandardCharsets.UTF_8));
      buffer.reset();
    } else {
      buffer.write(b);
    }
  }

  private void process(String message) {
    // YOUR CODE HERE
  }
};
System.setErr(new PrintStream(myCustomreportingStream, true, StandardCharsets.UTF_8));

A bunch of things are happening here:

  • We're defining a custom OutputStream which buffers everything sent to it, until it sees \n (which is "newline" in ASCII, UTF-8, and many other encodings), at which point it turns the buffer into a string, sends that string to the process method, and clears out the buffer. It also ignores \r to deal with \r\n which is windows-style newlines.

  • We then use that OutputStream as basis for a new PrintStream, and then set up syserr to use this printstream.

  • This code does not deal with anything that sends data to System.err but doesn't send a newline symbol.

  • Anytime anybody anywhere runs System.err.println, your process() method will be run.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72