I am working on an application with Angular (4+) and PHP and I have some doubts about the HTTP calls made to the server and how best to handle cases where the function returns with error.
I currently have this code (in JS / Angular) to make 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 do the creation of a new user, where before creating the user itself, I need to check some conditions, such as single e-mail, fields required, etc.
Currently what I do is check these conditions and return a response 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 interrupted before creating a user, it is treated as a function that has returned successfully. For this type of case I need to check the contents of the error message, like this:
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 every 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. / p>
What I tried to do was to interrupt the function using:
throw new Execption('mensagem aqui');
The problem with this method is that even then the response returned is success
, but with null
message, and the only place I can see the error message is opening the console and inspecting the call on the network
.
What I would like to do is to interrupt and return the PHP
function so that it is possible to handle these errors within the error callback , in my example, within the handleErrors
function. Therefore, only the functions that actually execute the entire process will be returned successfully.