Answer the question
In order to leave comments, you need to log in
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);
}
//отправляем приглашение
}
if ($user->isCustomer) {
return response()->json(['status' => 'error']);
} else {
return response()->json(['status' => 'ok']);
}
Answer the question
In order to leave comments, you need to log in
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);
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 questionAsk a Question
731 491 924 answers to any question