I am using playframework 2.6.x for my Java application.
When I detected that the user request is invalid I would like to return 4XX with meaningful message.
In my Controller I could just return badRequest("message");
But how do I do this somewhere deeper in the stack?
If I were using Scala the I could use Try or Either returns all the way to controller (even that is annoying depending on how deep in the stack we are talking about)
I was hoping that I can just throw new BadRequest("message");
that DefaultHttpExceptionHandler converts to HTTP 400 result; with appropriate message from the exception.
But I did not find such a thing.
I can be rolling my own exception handler and exception types. But was trying to avoid that if there is existing exception type that I can use.
class MyController {
Result myPutResourceHandler(req) {
// get A from request here
try {
someOtherObj.storeA(objA);
return ok("success");
} catch (IllegalArgumentException e) {
return badRequest(e.getMessage());
} catch (Throwable t) {
return serverError(t.getMessage);
}
}
}
class SomeOtherObj {
void storeA(A objA) {
if (!isValid(objA)) {
// need to cause bad request
throw new IllegalArgumentException("helpful message");
}
}
}
I am looking to throw new BadRequest() and not do any handling in my controller and not write any handler. This is not about how to handle client error but how to easily throw client error in my code.
I found play.mvc.results (Play! API)
It looks promising since Result is an exception.
But I do not find play.mvc.results package in my jars and could not find any examples of how to use that.
I don’t know much about Play 1.x but that’s what it looks like to me. The same kind of functionality can be easily achieved with my sample code though.