Error logging using filters

Example of logging errors using filters.To log just the errors we make objects of StringWriter and PrintStream and name it errorWriter and errorCapture. We then instantiate the given objects in beforeClass method.

import static io.restassured.RestAssured.given;
import java.io.PrintStream;
import java.io.StringWriter;
import org.apache.commons.io.output.WriterOutputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.filter.log.ErrorLoggingFilter;
import io.restassured.filter.log.RequestLoggingFilter;

public class FilterExample2 {
public static StringWriter errorWriter;
public static PrintStream errorCapture;
    
    
@BeforeClass
public void beforeEachMethod(){
errorWriter = new StringWriter();
errorCapture = new PrintStream(new WriterOutputStream(errorWriter),true);
}
    
@Test
    
public void getStudentData() throws JSONException{
RestAssured.baseURI = "http://localhost";
RestAssured.port = 8080;
RestAssured.basePath = "/student";
        

//Put filter in our get request to capture the error. Note we  will only get error if our get request fails. Like for example if we pass an id in get request that //does not exists like 10001 then the get request will say no record found. So that error can be captured using below line of code    

given().filter(new ErrorLoggingFilter(errorCapture)).when().get("/10001");
String request = errorWriter.toString();
      
System.out.println("----------------------------------------------------");

//Then we can print our filtered error log below
System.err.println(request);
        
  }    
}