From 9db1616dc2ccf7b6ca8356dcab171e97f13b7dfa Mon Sep 17 00:00:00 2001 From: Glenn Slotte Date: Thu, 12 Oct 2023 10:39:06 +0200 Subject: [PATCH 1/3] feat(core): add protect --- src/RescriptCore.res | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/RescriptCore.res b/src/RescriptCore.res index 0cdb0025..398f598d 100644 --- a/src/RescriptCore.res +++ b/src/RescriptCore.res @@ -68,3 +68,13 @@ type undefined<+'a> = Js.undefined<'a> type nullable<+'a> = Js.nullable<'a> let panic = Core__Error.panic + +let protect = (~finally, f) => { + let result = try f() catch { + | exn => + finally() + raise(exn) + } + finally() + result +} From 5853c922538d1a6d9bd235d7eb95d9a42df30386 Mon Sep 17 00:00:00 2001 From: glennsl Date: Mon, 30 Oct 2023 14:21:24 +0100 Subject: [PATCH 2/3] docs(core): documentation and example for protect --- src/RescriptCore.res | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/RescriptCore.res b/src/RescriptCore.res index 398f598d..174dde15 100644 --- a/src/RescriptCore.res +++ b/src/RescriptCore.res @@ -69,6 +69,22 @@ type nullable<+'a> = Js.nullable<'a> let panic = Core__Error.panic +/** + `protect(~finally, f)` + + Tries to execute the function `f`, and ensures that `finally` will be called + whether `f` raises an exception or not. + + Any exception raised by `f` will be re-raised in order to be handled by the + user. If `finally` raises, then that exception will be emitted instead, and + any exception raised by `f` will go unnoticed. + + ```res example + try protect(~finally=() => Js.log("finally"), () => failwith("oh no!")) catch { + | Failure(err) => Js.log(err) + } + ``` +*/ let protect = (~finally, f) => { let result = try f() catch { | exn => From 15a34c698e4fabdaf9714df470cc5109c5b840bb Mon Sep 17 00:00:00 2001 From: glennsl Date: Mon, 30 Oct 2023 14:22:15 +0100 Subject: [PATCH 3/3] chore: update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23dc8533..c84920c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### API changes - Add `Math.Int.floor` and `Math.Int.random`, https://github.com/rescript-association/rescript-core/pull/156 +- Add `protect` https://github.com/rescript-association/rescript-core/pull/155 ### Documentation