Reputation: 321
I want to return a JSON response instead of HTML. I dont know how to trap it. For example i set the 'play.http.parser.maxMemoryBuffer' to 1MB, and if the request body will exceed 1 MB, it will return a JSON response but not HTML format saying that it is a bad response.
Upvotes: 1
Views: 190
Reputation: 11
According to the documentation: To switch from HTML to JSON response you can add this line to application.conf
play.http.errorHandler = play.http.JsonHttpErrorHandler
If you also want to customize the message, you should instead add this line to application.conf
play.http.errorHandler = "com.example.ErrorHandler"
Obviously, the line above, should point to your own implementation of the error handler, that could look like this:
package com.example
import play.http.HttpErrorHandler;
import play.mvc.*;
import play.mvc.Http.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Singleton;
@Singleton
public class ErrorHandler implements HttpErrorHandler {
public CompletionStage<Result> onClientError(RequestHeader request, int statusCode, String message) {
if (statusCode == 413) {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message + " The payload size should be lower than 1Mb."));
} else {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message));
}
}
public CompletionStage<Result> onServerError(RequestHeader request, Throwable exception) {
return CompletableFuture.completedFuture(
Results.internalServerError("A server error occurred: " + exception.getMessage()));
}
}
Upvotes: 1