Manage errors in HTTP calls

Asked

Viewed 91 times

1

I am working on an application with Angular(4+) and PHP and I have some questions about the HTTP calls made to the server and how to better manage the cases where the function returns with error.

I currently have this code (in JS/Angular) to make the calls:

createUser(user: any): any {
    return this._http.post(this.backendUrl, user).map(response => {
        console.log('Mensagem de sucesso: ', response);
    }).catch(this.handleErrors);
}

handleErrors(error: Response): any {
    console.log('Gerenciar erro: ', error);
}

To better illustrate the situation, suppose I have a function, in PHP, to make the creation of a new user, where before creating the user itself, I need to check some conditions, such as single email, completed mandatory fields, etc..

Currently what I do is check these conditions and return a reply in JSON, for example:

$param = [':email' => $email];
$check = sql("SELECT 1 FROM users WHERE email = :email", $param);
if ( $check ) {
    return print_r(json_encode(array(
        'success' => 0,
        'message' => 'Este email já está registrado'
    ), JSON_NUMERIC_CHECK));
}

In this case, although there is an "error" during the execution of the function, causing it to be stopped before creating a user, it is treated as a function that has successfully returned. For this type of case I need to check the content of the error message, so:

return this._http.post(this.backendUrl, user).map(response => {
    console.log('Mensagem de sucesso: ', response);

    if(!response.success) {
        return alert(response.message);
    }

    lista_usuario.unshift(response.usuario); // Supondo que o usuário tenha sido criado
}).catch(this.handleErrors);

This method is working, however, as you can see, for each function I call (there are other similar cases), I need to check if the content returned as success is in fact a valid return or an error.


What I tried to do was to interrupt the function using:

throw new Execption('mensagem aqui');

The problem with this method is that even so the answer returns is a success, but with message of null and the only place I can view the error message is by opening the console and inspecting the call in the network.

What I’d like to do is interrupt and return the function PHP so that these errors can be dealt with within the callback error, in my example, within the function handleErrors. Therefore, only the functions that actually perform the whole process will be successfully returned.

  • Your premise seems to me quite wrong. Exceptions should be used for exceptional cases and not for processing validation rules.

  • @LINQ was what I imagined, but I don’t know so much about PHP to know if it is possible to get this result, or what would be the best method of processing this data/functions. In fact I don’t need to get stuck to a method, the important thing is the end result, or what is more "correct", if that can be said.

1 answer

0


I was able to "solve" the problem using the following code:

// No início do código, para retornar status 500 em qualquer erro não esperado.
ini_set('display_errors', 0);

// Antes de retornar uma função
http_response_code(401); // ou outro código. 404, 409, 420, etc...

Since I don’t know much about PHP, I will leave the question still open for a possible better option for the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.