Sync between error Listener and Test execution in WebDriver

I am trying to implement a javaScript error listener on the Selenium tests built in my Java project.

In order to detect console Java Script errors, I implemented a script in the JavaScript project which will push the console error messages at the bottom of the body, with a certain element containing a specific ID and the error message.

The error Listener I coded looks like:

public class ErrorListener implements Runnable{

    WebDriver driver = null;

    public ErrorListener (WebDriver driver)
    {
        this.driver = driver;
    }

    private void Listen ()
    {       
        try 
        {
            while(!driver.toString().contains("null")) //Chrome is alive
            {       

                List<WebElement> list = driver.findElements(By.xpath("//div[@id='jsError']"));

                if(list.size() != 0)
                {
                    WebElement Error = list.get(0);

                    String ErrorMSG = Error.getText();

                    if(ErrorMSG != null) 
                    {   

                        Reporter.log("Found a javascript error with code: "+ErrorMSG);
                        Assert.assertTrue(false); // force the test failure
                    }
                }
            }
        }catch(Exception ex) 
        {
            ex.printStackTrace();   
        }
    }

    @Override
    public void run() 
    {
        Listen();
    }
}

Which I am calling in my test method such as:

public class TC_NewAccount 
{
    public WebDriver driver;
    public Thread listener;
@BeforeMethod
public void beforeTest()
{
    Reporter.log("The test has just begun.");
    driver = NewChrome.Generate(true);

    ErrorListener errorlog = new ErrorListener(driver);
    listener = new Thread(errorlog);
    listener.start();
}
@AfterMethod
public void afterClass() 
{
    Reporter.log("Test has now finished.");
    driver.close();
}

@DataProvider
public static Object[][] credentials() 
{
    return new Object[][]   { {     "id",   "password"   }};
}
@Test(dataProvider = "credentials")
public void Execute(String username, String password) throws Exception 
{
... whatever the test does
}
}

The problem is, that since I am using the same instance of Chrome to constantly listen to a specific WebElement, I am throwing requests in parallel from both methods (the test and the listener), and the process ends up crashing because of them being at the same time and not being synced (one after another).

I realised that one option could be to check for errors after I do certain action every time, but this would greatly increment my lines of code, and it is only a partial solution because some errors may occur just in terms of milliseconds…

Is there a smooth solution for this problem?

Thanks in advance!

first of all you have to create you TestListener.java file

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class TestListener implements ITestListener {

@Override
public void onTestStart(ITestResult result) {
    System.out.println("Started Test: " + result.getName());
}

@Override
public void onTestSuccess(ITestResult result) {
    System.out.println("Finished Test: " + result.getName() + " :PASSED");
}

@Override
public void onTestFailure(ITestResult result) {
    System.out.println("Finished Test: " + result.getName() + " :FAILED");
}

@Override
public void onTestSkipped(ITestResult result) {
    System.out.println("Finished Test: " + result.getName() + " :SKIPPED");
}

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
    System.out.println("Finished Test: " + result.getName()
            + " :FAILED BUT WITHIN SUCCESS PERCENTAGE");
}

@Override
public void onStart(ITestContext context) {
    // TODO Auto-generated method stub

}
@Override
public void onFinish(ITestContext context) {
    // TODO Auto-generated method stub

}
}

you can customize this file according to you . Next what you have to do is you need to mention this listener in your Test class

@Listeners(TestListener.class)

public class TestClass{
@Test(dataProvider = "TestData" , dataProviderClass = DataProviderUtil.class)   
public void test(List data) throws Exception {

    try{

        // your code here

    }
    catch(Exception e){
        Log.exception(e);
    }finally {
        Log.endTestCase();
    }
}
}