Reputation: 1601
I'm using play 2.8.x framework
and I have the following controller:
public class HomeController extends Controller {
public Result show(Http.Request request) throws MyException {
...
return ok("some_data");
}
}
and I want to do something like in a Spring framework
for handling exceptions:
// It is from the Spring web framework
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExplainExceptionDTO handleMyException() {
...
return explain;
}
Can I do something like this in the play 2.8.x framework
?
Upvotes: 1
Views: 52
Reputation: 6501
This explains it pretty well: https://www.playframework.com/documentation/2.8.x/JavaErrorHandling
@Singleton
public class ErrorHandler implements HttpErrorHandler {
public CompletionStage<Result> onClientError(
RequestHeader request, int statusCode, String message) {
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()));
}
}
The method you are interested in is onServerError
. So instead of returning the default internalServerError check the Throwable type, if it's your exception return badRequest()
, you can even provide the template if you want.
Upvotes: 1