简体   繁体   中英

How to Customize ValidationException Response in Lumen?

I develop an REST API using Lumen. I thought using details key inside JSON object is convenient to show errors. See the response:

{"detail": "Something bad happened."}

Lumen has validation that you can call inside a controller as in $this->validate(["foo" => "required", "bar" => "required"}) . If I do not set foo value in the request body, the server naturally responds:

{
    "foo": [
        "The foo field is required."
    ]
}

However, I also want these to be inside details key so that it would be convenient for consumer. See the desired repsonse:

{
    "details": {
        "foo": [
            "The foo field is required."
        ]
    }
}

Is it possible to do this, if so, how?

Further Investigation

As Validation section in Lumen documentation states:

Should validation fail, the $this->validate helper will throw Illuminate\\Validation\\ValidationException with embedded JSON response that includes all relevant error messages.

That means somehow I need to extend ValidationException , but I still do not have any idea about how to trigger my CustomValidationException in $this->validate method.


Environment

  • PHP 7.3.5
  • Lumen 5.8

You can assign the result of $this->validate() to a variable and use that variable in your json response according to your choice. Like following:

 $validator = Validator::make($request->all(), [
            'foo' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json(['details'=> $validator->errors()->first() ], 400);
        }

400 here is json response. You may use it or not

In your App/Exception/Handler class, add these lines:

use Illuminate\Validation\ValidationException;

...

public function render($request, Throwable $exception) {
    ...

    if ($exception instanceof ValidationException) {
        return response()->json([
                    'details' => $exception->errors(),
        ], 422);
    }


    return parent::render($request, $exception);
}

And you still get the translated messages. Tested in Lumen 7.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM