CHIRANJIT BARDHAN
CHIRANJIT BARDHAN

Reputation: 151

How to throw custom http error in play framework java

Below is the code to save data. I want to throw http error code 422 if validation fails. But i am getting 200(OK) response. How to do that. Thanks

public Result saveBook()
    {
        Form<Book> bookForm = formFactory.form(Book.class).bindFromRequest();

        if(bookForm.hasErrors())
        {
            List<String> validationError = new ArrayList<>();

            ObjectNode result = Json.newObject();

            result.put("code", 422);
            result.put("status", "error");

            for(ValidationError e: bookForm.allErrors())
            {
                validationError.add(e.message());
            }

            result.put("errors", Json.toJson(validationError));

            return ok(result);
        }

        Book book = bookForm.get();
        book.save();

        return ok(Json.toJson(book));
    }

Upvotes: 1

Views: 1332

Answers (2)

Sky
Sky

Reputation: 41

just simply replace return ok(Json.toJson(book)); with return status(422)

OR you can use the link below to see what other options do you have besides the simplest status(422) form. https://www.playframework.com/documentation/2.0/api/java/play/mvc/Results.Status.html#Results.Status(play.api.mvc.Results.Status,%20byte[])

Upvotes: 1

glytching
glytching

Reputation: 47905

This line:

return ok(result);

... is telling Play to return an ok (i.e. HTTP status 200) result.

The play.mvc.Results class offers shortcuts such as:

  • ok()
  • notFound()
  • badRequest()
  • internalServerError()

It does not offer a shortcut for a 422 but you can easily create one: status(422, "...").

So, just replace ...

return ok(result);

... with:

return status(422, "your chosen status message");

Upvotes: 4

Related Questions