From 5b035f030c32238de62552cee112cddfd5f274c0 Mon Sep 17 00:00:00 2001 From: ockley Date: Tue, 24 Mar 2026 11:03:55 +0100 Subject: [PATCH] Oversat --- .../01-error-async/solution.md | 8 +- .../01-error-async/task.md | 6 +- .../04-promise-error-handling/article.md | 132 +++++++++--------- 3 files changed, 73 insertions(+), 73 deletions(-) diff --git a/1-js/11-async/04-promise-error-handling/01-error-async/solution.md b/1-js/11-async/04-promise-error-handling/01-error-async/solution.md index 0d43f55e0..a736bfa4d 100644 --- a/1-js/11-async/04-promise-error-handling/01-error-async/solution.md +++ b/1-js/11-async/04-promise-error-handling/01-error-async/solution.md @@ -1,13 +1,13 @@ -The answer is: **no, it won't**: +Svaret er: **nej, det vil ikke**: ```js run new Promise(function(resolve, reject) { setTimeout(() => { - throw new Error("Whoops!"); + throw new Error("Ups!"); }, 1000); }).catch(alert); ``` -As said in the chapter, there's an "implicit `try..catch`" around the function code. So all synchronous errors are handled. +Som sagt tidligere i kapitlet er der en "implicit `try..catch`" omkring funktionens kode. Det betyder at alle synkrone fejl håndteres. -But here the error is generated not while the executor is running, but later. So the promise can't handle it. +Men her genereres fejlen ikke mens udføreren kører, men senere. Så promise kan ikke håndtere den. diff --git a/1-js/11-async/04-promise-error-handling/01-error-async/task.md b/1-js/11-async/04-promise-error-handling/01-error-async/task.md index bafc47ce9..a57301665 100644 --- a/1-js/11-async/04-promise-error-handling/01-error-async/task.md +++ b/1-js/11-async/04-promise-error-handling/01-error-async/task.md @@ -1,11 +1,11 @@ -# Error in setTimeout +# Fejl i setTimeout -What do you think? Will the `.catch` trigger? Explain your answer. +Hvad tror du? Vil `.catch` blive udløst? Forklar dit svar. ```js new Promise(function(resolve, reject) { setTimeout(() => { - throw new Error("Whoops!"); + throw new Error("Ups!"); }, 1000); }).catch(alert); ``` diff --git a/1-js/11-async/04-promise-error-handling/article.md b/1-js/11-async/04-promise-error-handling/article.md index c5b4206ab..10bd36267 100644 --- a/1-js/11-async/04-promise-error-handling/article.md +++ b/1-js/11-async/04-promise-error-handling/article.md @@ -1,21 +1,21 @@ -# Error handling with promises +# Håndtering af fejl med promises -Promise chains are great at error handling. When a promise rejects, the control jumps to the closest rejection handler. That's very convenient in practice. +Kæder af promise er gode til fejlbehandling. Når et promise afvises, springer kontrollen til den nærmeste afvisningshåndtering. Det er meget praktisk i praksis. -For instance, in the code below the URL to `fetch` is wrong (no such site) and `.catch` handles the error: +For eksempel, i koden nedenfor er URL'en til `fetch` forkert (ingen sådan side) og `.catch` håndterer fejlen: ```js run *!* -fetch('https://no-such-server.blabla') // rejects +fetch('https://no-such-server.blabla') // afviser */!* .then(response => response.json()) - .catch(err => alert(err)) // TypeError: failed to fetch (the text may vary) + .catch(err => alert(err)) // TypeError: failed to fetch (teksten kan variere) ``` -As you can see, the `.catch` doesn't have to be immediate. It may appear after one or maybe several `.then`. +Som du kan se behøver `.catch` ikke at komme umiddelbart efter. Den kan sagtens placeres efter en eller flere `.then`. -Or, maybe, everything is all right with the site, but the response is not valid JSON. The easiest way to catch all errors is to append `.catch` to the end of chain: +Eller, måske er alt i orden med siden, men svaret er ikke gyldigt JSON. Den nemmeste måde at fange alle fejl er at tilføje `.catch` til slutningen af kæden: ```js run fetch('/article/promise-chaining/user.json') @@ -38,168 +38,168 @@ fetch('/article/promise-chaining/user.json') */!* ``` -Normally, such `.catch` doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it. +Normalt vil sådan en `.catch` slet ikke blive aktiveret. Men, hvis en af dine promises afvises (et netværksproblem, ugyldig json osv.), så vil den fange det. ## Implicit try..catch -The code of a promise executor and promise handlers has an "invisible `try..catch`" around it. If an exception happens, it gets caught and treated as a rejection. +Koden fra en promise udførerer og promise handlere har en "usynlig `try..catch`" omkring den. Hvis der sker en exception, vil den blive opfanget og behandlet som en afvisning. -For instance, this code: +Se for eksempel denne kode: ```js run new Promise((resolve, reject) => { *!* - throw new Error("Whoops!"); + throw new Error("Ups!"); */!* -}).catch(alert); // Error: Whoops! +}).catch(alert); // Error: Ups! ``` -...Works exactly the same as this: +...Virker præcis på samme måde som denne: ```js run new Promise((resolve, reject) => { *!* - reject(new Error("Whoops!")); + reject(new Error("Ups!")); */!* -}).catch(alert); // Error: Whoops! +}).catch(alert); // Error: Ups! ``` -The "invisible `try..catch`" around the executor automatically catches the error and turns it into rejected promise. +Den "usynlige `try..catch`" omkring udførerenopfanger automatisk fejl og omdanner dem til afviste løfter. -This happens not only in the executor function, but in its handlers as well. If we `throw` inside a `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler. +Det sker ikke kun i udførerfunktionen, men også i dens handlere. Hvis vi bruger `throw` indeni en `.then`-handler, betyder det en afvisning af løftet, og kontrollen overgives til den nærmeste fejlhåndterer. -Here's an example: +Her er et eksempel: ```js run new Promise((resolve, reject) => { resolve("ok"); }).then((result) => { *!* - throw new Error("Whoops!"); // rejects the promise + throw new Error("Ups!"); // afviser løftet */!* -}).catch(alert); // Error: Whoops! +}).catch(alert); // Error: Ups! ``` -This happens for all errors, not just those caused by the `throw` statement. For example, a programming error: +Dette sker for alle fejl, ikke kun de der er forårsaget af `throw`-sætningen. For eksempel, en programmeringsfejl: ```js run new Promise((resolve, reject) => { resolve("ok"); }).then((result) => { *!* - blabla(); // no such function + blabla(); // funktionen findes ikke */!* -}).catch(alert); // ReferenceError: blabla is not defined +}).catch(alert); // ReferenceError: blabla er ikke defineret ``` -The final `.catch` not only catches explicit rejections, but also accidental errors in the handlers above. +Den endelige `.catch` fanger ikke kun eksplicitte afvigelser, men også tilfældige fejl i de håndteringer, der kommer før den. ## Rethrowing -As we already noticed, `.catch` at the end of the chain is similar to `try..catch`. We may have as many `.then` handlers as we want, and then use a single `.catch` at the end to handle errors in all of them. +Som vi allerede har bemærket ligner en `.catch` i slutningen af kæden `try..catch`. Vi kan have så mange `.then` håndteringer som vi vil, og så bruge en enkelt `.catch` i slutningen for at håndtere fejl i alle af dem. -In a regular `try..catch` we can analyze the error and maybe rethrow it if it can't be handled. The same thing is possible for promises. +I en normal `try..catch` kan vi analysere fejlen og måske kaste den igen, hvis den ikke kan håndteres. Det samme er muligt for promises. -If we `throw` inside `.catch`, then the control goes to the next closest error handler. And if we handle the error and finish normally, then it continues to the next closest successful `.then` handler. +Hvis vi bruger `throw` indeni `.catch`, så går kontrollen til den næste tætteste fejl-handler. Og hvis vi håndterer fejlen og afslutter normalt, så fortsætter det til den næste tætteste succesfulde `.then` handler. -In the example below the `.catch` successfully handles the error: +I eksemplet nedenfor håndterer `.catch` fejlen succesfuldt: ```js run // the execution: catch -> then new Promise((resolve, reject) => { - throw new Error("Whoops!"); + throw new Error("Ups!"); }).catch(function(error) { - alert("The error is handled, continue normally"); + alert("Fejlen er håndteret, fortsæt normalt"); -}).then(() => alert("Next successful handler runs")); +}).then(() => alert("Næste succesfulde handler kører")); ``` -Here the `.catch` block finishes normally. So the next successful `.then` handler is called. +Her afsluttes `.catch` blokken normalt. Så den næste succesfulde `.then` handler kaldes. -In the example below we see the other situation with `.catch`. The handler `(*)` catches the error and just can't handle it (e.g. it only knows how to handle `URIError`), so it throws it again: +I eksemplet nedenfor ser vi den anden situation med `.catch`. Handleren `(*)` fanger fejlen og kan ikke håndtere den (f.eks. den kun ved hvordan man håndterer `URIError`), så den kaster den igen: ```js run // the execution: catch -> catch new Promise((resolve, reject) => { - throw new Error("Whoops!"); + throw new Error("Ups!"); }).catch(function(error) { // (*) if (error instanceof URIError) { - // handle it + // håndter fejlen } else { - alert("Can't handle such error"); + alert("Kan ikke håndtere sådan en fejl"); *!* - throw error; // throwing this or another error jumps to the next catch + throw error; // kaster fejlen videre */!* } }).then(function() { - /* doesn't run here */ + /* denne handler kører ikke her */ }).catch(error => { // (**) - alert(`The unknown error has occurred: ${error}`); - // don't return anything => execution goes the normal way + alert(`En ukendt fejl er opstået: ${error}`); + // returnerer ikke noget => udførelse foregår normalt }); ``` -The execution jumps from the first `.catch` `(*)` to the next one `(**)` down the chain. +Udførelse foregår fra den første `.catch` `(*)` til den næste `(**)` ned ad kæden. -## Unhandled rejections +## Afvisninger der ikke håndteres -What happens when an error is not handled? For instance, we forgot to append `.catch` to the end of the chain, like here: +Hvad sker der når en fejl ikke håndteres? For eksempel, vi har glemt at tilføje `.catch` til slutningen af kæden, som her: ```js untrusted run refresh new Promise(function() { - noSuchFunction(); // Error here (no such function) + noSuchFunction(); // Fejl her (funktionen findes ikke) }) .then(() => { - // successful promise handlers, one or more - }); // without .catch at the end! + // håndtering af succesfuld promise, en eller flere + }); // men uden .catch i slutningen! ``` -In case of an error, the promise becomes rejected, and the execution should jump to the closest rejection handler. But there is none. So the error gets "stuck". There's no code to handle it. +I tilfælde af en fejl, bliver løftet afvist, og udførelsen vil prøve at hoppe til den nærmeste håndtering af afvisninger - men der er ingen. Så fejlen bliver "fastlåst". Der er ingen kode til at håndtere den. -In practice, just like with regular unhandled errors in code, it means that something has gone terribly wrong. +I praksis, ligesom med regulære uhåndterede fejl i kode, betyder det, at noget er gået frygteligt galt. -What happens when a regular error occurs and is not caught by `try..catch`? The script dies with a message in the console. A similar thing happens with unhandled promise rejections. +Hvad sker der når en regulær fejl opstår og ikke bliver fanget af `try..catch`? Scriptet dør med en besked i konsollen. Et lignende noget sker med uhåndterede promise-afvisninger. -The JavaScript engine tracks such rejections and generates a global error in that case. You can see it in the console if you run the example above. +JavaScript-motoren sporer sådanne afvisninger og genererer en global fejl i det tilfælde. Du kan se det i konsollen, hvis du kører eksemplet ovenfor. -In the browser we can catch such errors using the event `unhandledrejection`: +I browseren kan vi fange sådanne fejl ved hjælp af begivenheden `unhandledrejection`: ```js run *!* window.addEventListener('unhandledrejection', function(event) { - // the event object has two special properties: - alert(event.promise); // [object Promise] - the promise that generated the error - alert(event.reason); // Error: Whoops! - the unhandled error object + // et event objekt har to specielle egenskaber: + alert(event.promise); // [object Promise] - det promise der genererede fejlen + alert(event.reason); // Error: Ups! - det error objekt der ikke er behandlet }); */!* new Promise(function() { - throw new Error("Whoops!"); -}); // no catch to handle the error + throw new Error("Ups!"); +}); // ingen cathc til at opfange fejlen ``` -The event is the part of the [HTML standard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections). +Event'et er en del af [HTML standarden](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections). -If an error occurs, and there's no `.catch`, the `unhandledrejection` handler triggers, and gets the `event` object with the information about the error, so we can do something. +Hvis der sker en fejl og der ikke er en `.catch`, vil handleren `unhandledrejection` blive udløst og modtage et `event` objekt med information om fejlen, så vi kan handle på det. -Usually such errors are unrecoverable, so our best way out is to inform the user about the problem and probably report the incident to the server. +Normalt er det ikke muligt at komme sig over sådanne fejl, så vores bedste måde at håndtere dem på er at informere brugeren om problemet og sandsynligvis rapportere hændelsen til serveren. -In non-browser environments like Node.js there are other ways to track unhandled errors. +I ikke-browser miljøer som Node.js findes der andre måder at spore uhåndterede fejl på. -## Summary +## Opsummering -- `.catch` handles errors in promises of all kinds: be it a `reject()` call, or an error thrown in a handler. -- `.then` also catches errors in the same manner, if given the second argument (which is the error handler). -- We should place `.catch` exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and rethrow unknown ones (maybe they are programming mistakes). -- It's ok not to use `.catch` at all, if there's no way to recover from an error. -- In any case we should have the `unhandledrejection` event handler (for browsers, and analogs for other environments) to track unhandled errors and inform the user (and probably our server) about them, so that our app never "just dies". +- `.catch` håndterer fejl i alle slags promises: det kan være en `reject()` der kaldes eller en fejl der kastes med `throw`. +- `.then` kan også opfange fejl på samme måde, hvis den får et andet argument (som er fejlhåndteringen). +- Vi bør placere `.catch` præcis på de steder vi vil håndtere fejlene og ved hvordan de skal behandles. Den handler der skal skal analysere fejlen (brugerdefinerede fejl kan hjælpe) og kaste fejl den ikke kender videre (rethrow) da det kan være programmeringsfejl. +- Det er ok slet ikke at bruge `.catch` hvis der ikke er nogen måde at afhjælpe fejl. +- I alle tilfælde bør vi have en `unhandledrejection` event handler (for browsere og tilsvarende for andre miljøer) til at opsnappe fejl der ikke håndteres og informere brugeren (og muligvis serveren) om dem, så vores app ikke bare "dør uden grund".