question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do I get validation to throw an exception which I can handle?

See original GitHub issue

Hi,

I’m using Javalin (java) version.

I’m using the BodyValidator to coerce a JSON into a class (in this case Customer.class).

I do a few chained check()s.

I want it so that if a check fails that an exception is thrown (potentially with the corresponding error message), so that I can handle it with an exception mapper, and I can return our standard “enveloped response.”

First I’ll show what I mean using curl examples:

Successful POST:

$ curl -i -XPOST -d '{"first_name": "john", "last_name": "doe", "email": "johndoe@example.com"}' http://127.0.0.1:7000/v1/customers; echo
HTTP/1.1 200 OK
Date: Tue, 11 Jun 2019 06:49:15 GMT
Server: Javalin
Content-Type: application/json
Content-Length: 140

{
  "success": true,
  "response": {},
  "timing": [],
  "messages": [
    "customer created"
  ],
  "time": "2019-06-11T06:49:15.479452Z"
}

Invalid POST:

HTTP/1.1 400 Bad Request
Date: Tue, 11 Jun 2019 06:49:24 GMT
Server: Javalin
Content-Type: text/plain
Content-Length: 73

Request body as Customer invalid - 'email' needs to be a non-empty string

For the invalid post I want:

{
  "success": true,
  "response": {},
  "timing": [],
  "messages": [
    "Request body as Customer invalid - 'email' needs to be a non-empty string"
  ],
  "time": <some time>
}

This is the code snippet for how the /v1/customer route is handled:

app.routes(() -> {
    path("/", () -> {
        get("/", ctx -> ctx.result("Hello World"));
        get("/health-check", ctx -> {
            var r = new Envelope(true, new HealthCheckResult(port), null, null);
            ctx.json(r);
        });
    });
    path("/v1", () -> {
        get("/health-check", ctx -> {
            var r = new Envelope(true, new HealthCheckResult(port), null, null);
            ctx.json(r);
        });
        post("/customers", ctx -> {
            var c = ctx.bodyValidator(Customer.class)
                .check(v -> v.getFirstName() != null && !v.getFirstName().isEmpty(), "'first_name' needs to be a non-empty string")
                .check(v -> v.getLastName() != null && !v.getLastName().isEmpty(), "'last_name' needs to be a non-empty string")
                .check(v -> v.getEmailAddress() != null && !v.getEmailAddress().isEmpty(), "'email' needs to be a non-empty string")
                .get();
            // Envelope(success=true, response=null, timing=null, messages=["customer created"])
            var r = new Envelope(true, null, null, List.of("customer created"));
            ctx.json(r);
        });
    });
});

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
nnathancommented, Jun 11, 2019

I also think that the validator is fail fast atm, so you would only get one error.

I guess then I should just skip the chained checks and do custom validation and return the custom Envelope() JSON then.

Thanks for the info.

0reactions
papadakocommented, Oct 26, 2021
Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it a good or bad idea throwing Exceptions when validating ...
The validation pass could collect up any number of exceptions representing EVERYTHING that's wrong with a particular input data set. Then it would...
Read more >
Validation - Throw Exception or Return False? - Jenkov.com
When validating input data you do not always have to throw an exception if the input is invalid. How to handle invalid data...
Read more >
How do I get validation to throw an exception which I can ...
Hi, I'm using Javalin (java) version. I'm using the BodyValidator to coerce a JSON into a class (in this case Customer.class).
Read more >
A Better Way to Handle Validation Errors - Kevin Smith
First, exceptions give the application a fail-on-first-problem behavior, which means that even though there's a possibility of multiple ...
Read more >
Replacing Throwing Exceptions with Notification in Validations
My first step is to split the check method into two parts, an inner part that will eventually deal only with notifications and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found