danyal14's avatar

Lumen request error message wrapper

I am trying to wrap request validation errors in custom response.

When validating request

// Since request breaks here when post is not valid, I can't capture error response.

$this->validate($request, [
            'name' => 'required',
            'link' => 'required'
        ], [
            'required' => ':attribute, is required.'
        ]);
// Actual validator response
{
    "name": [
        "name, is required."
    ],
    "link": [
        "link, is required."
    ]
}
// Actual validator response
{
    "errors": {
    "name": [
        "name, is required."
    ],
    "link": [
        "link, is required."
    ]
}
}

I tried to capture errors in BaseController to generic solution but didn't work, any suggestions?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

You can override the render method here: https://github.com/laravel/lumen/blob/master/app/Exceptions/Handler.php

In general this is Laravel specific, but you will end up with something like this

// app/Exceptions/Handler.php

class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof ValidationException) {
            // Return your custom response here
            // You can get all the data using $exception->errors();
        }

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

Please or to participate in this conversation.