美文网首页
How to read exception message fr

How to read exception message fr

作者: coolala | 来源:发表于2020-11-22 14:33 被阅读0次

For Java, we cannot simply catch exception from other thread.
For example, with JUnit, we want to catch an exception from other threads in a unit test. Cannot do that directly.
But we can use stdout as a "bridge".

// In the other thread
// use slf4j Logger

throw new Exception("exception message");
Logger.error("exception message");

With slf4j logger, the exception message will be showed in console when doing unit test.

Then we can redirect the system out to PrintStream.

// Unit test
public class Test {
    PrintStream console = null; // set output stream
    PrintStream stdout = System.out;
    ByteArrayOutputStream bytes = null; // buffer the messages from console
    

    @Before
    public void reset() {
        bytes = new ByteArrayOutputStream(); // assign memory
        System.setOut(new PrintStream(bytes)); // redirect the message from Console to bytes
    }

    @After
    public void tearDown() {
        System.setOut(stdout);
    }

    @Test
    public void catchExceptionMessage() {
        assertTrue(bytes.toString().contains("key message"));
    }
}

BTW, there is a useful way to catch un-caught exception within the SAME thread, good to know but doesn't relate to this issue.

Thread.UncaughtExceptionHandler

ref: JUnit 测试时,如何截获 Console 的输出

相关文章

网友评论

      本文标题:How to read exception message fr

      本文链接:https://www.haomeiwen.com/subject/ekyuiktx.html