Error Handling and Logging
When testing APIs, it is important to:
- Catch and manage errors gracefully.
- Log details to understand what went wrong.
In this tutorial, you will learn:
- Why Error Handling is Important
- Handling API Errors with REST Assured
- Logging Requests and Responses
- Logging Errors for Debugging
- Custom Error Messages
- Using Try-Catch for Error Handling
Why Error Handling is Important
APIs can fail due to many reasons:
- Invalid inputs (e.g., wrong data format)
- Server issues (e.g., 500 Internal Server Error)
- Authentication problems (e.g., 401 Unauthorized)
- Resource not found (e.g., 404 Not Found)
Good error handling helps you:
- Identify and fix problems faster.
- Get clear error messages during test failures.
- Ensure your tests are robust and reliable.
Handling API Errors with REST Assured
When calling an API, you must check for expected and unexpected responses.
Example: Handling a 404 Error (Resource Not Found)
Java
Copy
given()
.when()
.get("http://192.xxx.xx.xxx:8080/books/20250401")
.then()
.statusCode(404) // Check if resource is not found
.body("error", equalTo("Book not found"));
Example: Handling 400 (Bad Request)
If the API expects specific data, sending the wrong input returns 400 Bad Request.
Java
Copy
given()
.contentType("application/json")
.body("{\"name\": \"\"}") // Invalid input (empty name)
.when()
.post("https://api.example.com/users")
.then()
.statusCode(400)
.body("message", containsString("Invalid name"));
Logging Requests and Responses
REST Assured provides built-in methods to log:
- Requests (what you send)
- Responses (what you receive)
- Errors (in case of failures)
Log Everything (Request and Response)
Java
Copy
given()
.log().all() // Logs full request
.when()
.get("http://192.xxx.xx.xxx:8080/books/20250401")
.then()
.log().all() // Logs full response
.statusCode(200);
Log Only Errors
Logs only if the test fails.
Java
Copy
given()
.log().ifValidationFails() // Log only if there is a failure
.when()
.get("http://192.xxx.xx.xxx:8080/books/123")
.then()
.statusCode(200); // This will fail and log the error
Log Request Details
Log only the request (helpful for debugging).
Java
Copy
given()
.log().method() // Log HTTP method (GET, POST, etc.)
.log().uri() // Log the request URL
.log().headers() // Log headers
.log().body() // Log request body (for POST/PUT)
.when()
.post("https://api.example.com/create");
Log Response Details
Log only the response.
Java
Copy
given()
.when()
.get("http://192.xxx.xx.xxx:8080/books/20250401")
.then()
.log().status() // Logs status code (200, 404, etc.)
.log().headers() // Logs response headers
.log().body(); // Logs the response body
Custom Error Messages
Add custom messages to make errors clearer.
Example: Custom Error Message
Java
Copy
given()
.when()
.get("http://192.xxx.xx.xxx:8080/books/20250401")
.then()
.statusCode(200)
.body("name", equalTo("book 1"), "Name mismatch error!");
If the name does not match, you'll see:
java.lang.AssertionError: Name mismatch error!
Using Try-Catch for Error Handling
You can wrap your API calls in a try-catch block to handle exceptions.
Example: Handling Exceptions Gracefully
Java
Copy
try { Response response = given() .when() .get("http://192.xxx.xx.xxx:8080/books/20250401"); if (response.statusCode() != 200) { System.out.println("Error: Unexpected Status Code " + response.statusCode()); } else { System.out.println("Success: " + response.asString()); } } catch (Exception e) { System.out.println("Exception occurred: " + e.getMessage()); }
Example: Retry on Failure
If an API is unstable, you may retry it.
Java
Copy
int retries = 3; boolean success = false; for (int i = 0; i < retries; i++) { try { given() .when() .get("https://api.example.com/status") .then() .statusCode(200); success = true; break; // Exit loop if successful } catch (Exception e) { System.out.println("Retrying... Attempt: " + (i + 1)); } } if (!success) { throw new RuntimeException("API failed after " + retries + " retries"); }
Handling JSON Parsing Errors
If the response is not in the expected format, it can cause parsing errors.
Example: Safely Parse JSON
Java
Copy
try { Response response = given() .when() .get("https://api.example.com/data"); String value = response.jsonPath().getString("nonExistingField"); System.out.println("Value: " + value); } catch (Exception e) { System.out.println("Parsing Error: " + e.getMessage()); }
Validating Response Time
Ensure the API responds within a specific time.
Java
Copy
given()
.when()
.get("https://api.example.com/health")
.then()
.time(lessThan(3000L)); // Response must be under 3 seconds