W
W
WebDev2019-07-08 11:27:39
API
WebDev, 2019-07-08 11:27:39

Do I need to return an error from the rest api?

I am making a method that sends an invitation to the user, but the method has checks in which the invitation will not be sent. Is it necessary to throw an error if the check failed, or is it more correct to send a text with an error and status 200?

public function invite()
{
    $email = request()->input('email');

    $user = User::where('email', $email)->first();

    if ($user->isCustomer) {
        abort(403);
    }

    //отправляем приглашение
}

The code checks if the user is a buyer, but this is not an error.
That is, instead of abort(403), I could return status 200 with a response body, for example:
if ($user->isCustomer) {
    return response()->json(['status' => 'error']);
} else {
    return response()->json(['status' => 'ok']);
}

Accept on the client and parse the response.
How right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Zhuk, 2019-07-08
@kirill-93

In theory, the 403 Forbidden code is suitable here, because the use of this method is prohibited for a user with a certain role. Well, to make it clear why the response is 403, you can do this:
Well, or 422 Unprocessable Entity can be sent if the check is not on the role of the user who sends the request, but on the role of the user to whom the invite is sent. Then, in essence, this is a validation error:

return response()->json(['error' => 'The required user is a customer.'], 422);

L
Lone Ice, 2019-07-09
@daemonhk

Errors are of 2 types: server and client. If you get a server one (404, 500, etc), give a generic message saying "Something went wrong". If the error is client -side (the user was not found, the user has the wrong rights), give your messages for each case. The end user should clearly see what he is doing wrong, and not these intricacies of yours in the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question