bremg
bremg

Reputation: 48

Laravel send json response from inner function

So Im building an API. But I keep running into returning a json response from an inner function.

If I do the following then laravel sends a backlog or error log to the client. That should never ever happen in a api. So how do you do this in Laravel?

I want to return json immediately and stop excecuting without showing the client any other information

public function functionThatIsCalledByClient($data)
{
     $this->validateSomething($data);
}

private function validateSomething($data)
{
    if(! $data ) ) return response()->json(['error' => 'some message'], 400)->send();

    return true;
}

Upvotes: 1

Views: 1167

Answers (2)

Vadym UA
Vadym UA

Reputation: 44

throw new GeneralException('invalid required extra quantity');

Upvotes: 0

user8555937
user8555937

Reputation: 2387

You could use abort helper for that or, for complex cases, error handling.

In case of abort:

private function validateSomething($data)
{
    if(! $data )  // you can create a custom helper function to wrap this code.
       abort(400, json_encode(['error'=>'some error']), ['Content-Type: application/json']);

    return true;
}

In case of general handler:

private function validateSomething($data)
{
    if(! $data ) 
       throw new \Exception('some message');

    return true;
}

Inside app/Exceptions/Handler.php @ render

public function render($request, Exception $e)
{
    if($e instanceof Exception)
        return response()
                ->json(['error' => $e->getMessage()], 400);
                //->send(); should not be necessary
}

Upvotes: 2

Related Questions