aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html')
-rw-r--r--files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html138
1 files changed, 138 insertions, 0 deletions
diff --git a/files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html b/files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html
new file mode 100644
index 0000000000..a39d4576d7
--- /dev/null
+++ b/files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html
@@ -0,0 +1,138 @@
+---
+title: Promise.prototype.catch()
+slug: Web/JavaScript/Reference/Global_Objects/Promise/catch
+translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch
+---
+<div>{{JSRef}}</div>
+
+<div>O método <strong>catch()</strong> retorna uma Promise e lida apenas com casos rejeitados. Ele possui o mesmo comportamento de quando chamamos {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (de fato, chamando <code>obj.catch(onRejected)</code> internamente é chamado <code>obj.then(undefined, onRejected)</code>).</div>
+
+<h2 id="Sintaxe">Sintaxe</h2>
+
+<pre class="syntaxbox notranslate"><var>p.catch(onRejected)</var>;
+
+p.catch(function(motivo) {
+ // rejeição
+});
+</pre>
+
+<h3 id="Parâmetros">Parâmetros</h3>
+
+<dl>
+ <dt>onRejected</dt>
+ <dd>Uma {{jsxref("Function")}} chamada quando a <code>Promise</code> é rejeitada. Esta função possui um argumento:<br>
+ <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);"><strong>reason</strong></span></font> da rejeição.<br>
+       O motivo da rejeição.<br>
+ <br>
+ A Promise retornada pelo <code>catch()</code> é rejeitada apenas se <code>onRejected</code> cospe um erro ou se o o retorno da Promise foi rejeitada por si mesmo, ou seja, foi resolvida.</dd>
+</dl>
+
+<h3 id="Valor_de_retorno">Valor de retorno</h3>
+
+<p>Internamente chamamos <code>Promise.prototype.then</code> sobre o objeto que é chamando passando parâmetros como <code>undefined</code> e <code>onRejected</code> no manipulador de eventos. Então retornamos o valor da chamada que é {{jsxref("Promise")}}.</p>
+
+<div class="warning">
+<p>O exemplo abaixo está cuspindo uma string. Isso é considerado uma má prática. Sempre cuspir uma instance de erro (Error). Em todo caso, a parte que faz a captura deve fazer verificaçoes sobre os argumentos para saber se é uma string ou um erro e você poderá perder informações valiosas como stack traces.</p>
+</div>
+
+<p><strong>Demonstração de uma camada interna:</strong></p>
+
+<pre class="brush: js notranslate">// Sobrescrevendo o techo original de  Promise.prototype.then/catch adicionando alguns logs
+(function(Promise){
+    var originalThen = Promise.prototype.then;
+    var originalCatch = Promise.prototype.catch;
+
+    Promise.prototype.then = function(){
+        console.log('&gt; &gt; &gt; &gt; &gt; &gt; chamando .then em %o com argumentos: %o', this, arguments);
+        return originalThen.apply(this, arguments);
+    };
+    Promise.prototype.catch = function(){
+        console.log('&gt; &gt; &gt; &gt; &gt; &gt; chamando .catch em %o com argumentos: %o', this, arguments);
+        return originalCatch.apply(this, arguments);
+    };
+
+})(this.Promise);
+
+
+// chamando um catch em uma Promise já resolvida.
+Promise.resolve().catch(function XXX(){});
+
+// logs:
+// &gt; &gt; &gt; &gt; &gt; &gt; chamando .catch na Promise{} com os argumentos: Arguments{1} [0: function XXX()]
+// &gt; &gt; &gt; &gt; &gt; &gt; chamando .then na Promise{} com os argumentos: Arguments{2} [0: undefined, 1: function XXX()]</pre>
+
+<h2 id="Description">Description</h2>
+
+<p>O método <code>catch</code> pode ser útil para manipulação de erros na composição da sua promise.</p>
+
+<h2 id="Exemplos">Exemplos</h2>
+
+<h3 id="Usando_o_método_catch">Usando o método <code>catch</code></h3>
+
+<pre class="brush: js notranslate">var p1 = new Promise(function(resolve, reject) {
+  resolve('Sucesso');
+});
+
+p1.then(function(value) {
+  console.log(value); // "Sucesso!"
+  throw 'Ah, não!';
+}).catch(function(e) {
+  console.log(e); // "Ah, não!"
+}).then(function(){
+  console.log('Após um catch, a sequencia é restaurada');
+}, function () {
+  console.log('Não engatilhado devido ao catch');
+});
+
+// O seguinte se comporta da mesma maneira que o anterior
+p1.then(function(value) {
+  console.log(value); // "Sucesso!"
+ return Promise.reject('Ah, não!');
+}).catch(function(e) {
+  console.log(e); // "Ah, não!"
+}).then(function(){
+  console.log('Após um catch, a sequencia é restaurada');
+}, function () {
+  console.log('Não engatilhado devido ao catch');
+});
+
+</pre>
+
+<h2 id="Especificações">Especificações</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Especificação</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comentário</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td>
+ <td>{{Spec2('ES6')}}</td>
+ <td>Initial definition in an ECMA standard.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2>
+
+
+
+<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>
+
+<p>{{Compat("javascript.builtins.Promise.catch")}}</p>
+
+
+
+<h2 id="Veja_também">Veja também</h2>
+
+<ul>
+ <li>{{jsxref("Promise")}}</li>
+ <li>{{jsxref("Promise.prototype.then()")}}</li>
+</ul>