S
S
Sergey Ilichev2021-04-06 17:38:51
PHP
Sergey Ilichev, 2021-04-06 17:38:51

How to correctly use exception in api and is it necessary at all?

Hello colleagues.

In practice, I often meet completely different approaches to error handling, in particular in api services.
Somewhere they throw exceptions, somewhere they return an array like this in jason

if (!Yii::$app->request->isPost) {
    return ['result' => 'error', 'message' => 'POST only', 'code' => 405];
}

if (!$guid = Yii::$app->request->post('guid')) {
    return ['result' => 'error', 'message' => 'Guid required', 'code' => 400];
}

if (!$reason = Yii::$app->request->post('reason')) {
    return ['result' => 'error', 'message' => 'Reason required', 'code' => 400];
}


How to do it right? Throw an exception in the api and catch it in the client try-catch and process it? Do all exceptions need to be thrown and processed at all? For example, in this example, where the absence of some parameter in post is critical, what is the right thing to do? If it's not difficult, describe what, in your opinion, is better and more correct in this case, how you would do it on the API side and on the client side (another microservice in php).

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2021-04-06
@first-programmer

and how are you going to catch the exceptions on the server on the client?
if something went wrong on the server, it must inform the client about it. and how to process this answer, the task of the client.

A
Anton Shamanov, 2021-04-07
@SilenceOfWinter

you can not reinvent the wheel and use swagger

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question