Unable to catch exception from assert method using Respect Validation

435 views Asked by At

I'm using Respect Validation to attempt to validate data sent via a POST request. In doing so I discovered an issue where an exception in the Respect Validation library is not being caught.

$postValidator = v::key('name', v::stringType()->length(3, 50))
                 ->key('email', v::email())
                 ->key('contact', v::phone())
                 ->key('message', v::stringType()->length(7, 1000));

try {
    $isValid = $postValidator->assert(['random' => 'thing']);
} catch(Exception $exception) {
    return $response->withJson([
        'success' => false
    ]);
}

Testing the following returns the following error:

All of the required rules must pass for { "random": "thing" }

Here I've used a generic Exception that should catch any exception that occurs within the assert method. But it appears it doesn't and I'm getting a generic Slim error, instead of a JSON response:

enter image description here

Any ideas why I cannot catch that exception?

The problem I am having is Respect Validation will throw an exception if a naughty users was to input postdata that the app can not handle. Personally I'd rather respect validation just ignore those, but it doesn't. So I want to catch the exception that Respect throws when a user passes undefined post data and return a response. Except, in the code above the exception isn't being caught.

1

There are 1 answers

0
Nipuna On

I know the question is old, but I encountered the same problem and this is how I resolved it. I hope someone might find the helpful. For me it worked as follows,

$input = [ 
    'title' => 1
    'description' => "Validator test"
    'author' => "nipuna"
];

$postValidator = Valid::key('title',Valid::length(2,30)->stringType())
                    ->key('description',Valid::stringType())
                    ->key('author',Valid::intType()->length(1,2))
                    ->key('user',Valid::intType()->length(1,2));
try {
    $isValid = $postValidator->assert($input);
    // Do something with it
} catch (NestedValidationException $e) {
    http_response_code(400);
    echo json_encode([
        'error' => $e->getMessages()
    ]);
}

The result was,

{
    "error": {
        "title": "title must be of type string",
        "author": "author must have a length between 1 and 2",
        "user": "user must be present"
    }
}

The only change I've done is, changing the way I'm getting errors in the catch. You can catch the exception just by using Exception in the catch too as extended Exceptions would fall back to native PHP Exception. But getMessages() is a part of NestedValidationException. So using that would be appropriate in the catch.

So in your case since there are no matching keys in your array, it should display {{key}} must be present