vavr_使用Vavr在Java 8流中更好的異常處理

vavr

by Rajasekar Elango

由Rajasekar Elango

In this post, I will provide tips for better exception handling in Java 8 streams using the Functional Java library Vavr.

在這篇文章中,我將提供使用Functional Java庫Vavr在Java 8流中更好地處理異常的技巧。

問題 (The problem)

To illustrate with an example, let’s say we want to print the day of the week for a given stream of date strings in the format MM/dd/YYYY.

為了舉例說明,假設我們要以MM/dd/YYYY格式打印給定日期字符串流的星期幾。

初始解決方案 (Initial solution)

Let’s start with an initial solution, as seen below, and iteratively improve on it.

讓我們從一個初始解決方案開始,如下所示,然后對其進行迭代改進。

This will output

這將輸出

Huh, if a date string is invalid, this fails at the first DateTimeParseException without continuing with valid dates.

呵呵 ,如果日期字符串是無效的,這未能在第一DateTimeParseException沒有與有效日期繼續。

Java 8搶救之選 (Java 8 Optional to the rescue)

We can refactor parseDate to return Optional<LocalDate> to make it discard invalids and continue processing valid dates.

我們可以重構parseDate以返回Optional<LocalDa te>,以使其放棄無效值并繼續處理有效日期。

This will skip errors and converts all the valid dates.

這將跳過錯誤并轉換所有有效日期。

WEDNESDAY Text '01-01-2015' could not be parsed at index 2 THURSDAY Text 'not a date' could not be parsed at index 0 FRIDAY

This is a great improvement, but the exception has to be handled within the parseDate method and can’t be passed back to the main method to deal with it. We can’t make the parseDate method throw a checked exception as the Streams API doesn’t play well with methods that throw exceptions.

這是一個很大的改進,但是必須在parseDate方法中處理異常,并且不能將其傳遞回main方法進行處理。 我們不能使parseDate方法拋出檢查異常,因為Streams API與拋出異常的方法不能很好地配合使用。

Vavr的Try Monad更好的解決方案 (A better solution with Vavr’s Try Monad)

Vavr is a functional library for Java 8+. We will use the Try object from Vavr, which can be either an instance of Success or Failure. Basically Try is a monadic container type which represents a computation that may either result in an exception, or return a successfully computed value. Here is the modified code using Try:

Vavr是Java 8+的功能庫。 我們將使用Vavr中的Try對象,該對象可以是SuccessFailure的實例。 基本上, Try是一種Monadic容器類型,它表示可能導致異常或返回成功計算值的計算。 這是使用Try修改的代碼:

The output is

輸出是

WEDNESDAY Failed due to Text '01-01-2015' could not be parsed at index 2 THURSDAYFailed due to Text 'not a date' could not be parsed at index 0 FRIDAY

Now the exception is passed back to main to deal with it. Try also has APIs to implement recovery logic or return a default value in case of error.

現在,異常被傳遞回main進行處理。 Try還提供API來實現恢復邏輯或在出現錯誤的情況下返回默認值。

To demonstrate this, let’s say we also want to support MM-dd-YYYY as an alternate string format for dates. The below example shows how we can easily implement recovery logic.

為了說明這一點,假設我們還希望支持MM-dd-YYYY作為日期的備用字符串格式。 以下示例顯示了我們如何輕松實現恢復邏輯。

The output shows that now the date 01-01-2015 is also successfully converted.

輸出顯示,現在日期01-01-2015也已成功轉換。

WEDNESDAY THURSDAY THURSDAY Failed due to Text 'not a date' could not be parsed at index 0 FRIDAY

So Try Monad can be used to elegantly deal with exceptions and fail fast on errors.

因此, Try Monad可以用于優雅地處理異常,并在發生錯誤時快速失敗

Update on 12/03/2018:

2018年12月3日更新:

The code examples are updated to use Doculet.

代碼示例已更新為使用Doculet 。

Originally published at http://erajasekar.com/posts/better-exception-handling-java8-streams-using-javaslang/.

最初發布在http://erajasekar.com/posts/better-exception-handling-java8-streams-using-javaslang/中 。

翻譯自: https://www.freecodecamp.org/news/better-exception-handling-in-java-8-streams-using-vavr-6eda31285ce9/

vavr

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394019.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394019.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394019.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python-strace命令追蹤ssh操作

Python-strace命令追蹤ssh操作 通過strace 命令追蹤ssh的進程ID&#xff0c;記錄操作的命令[實際上是內核里面記錄的東西]&#xff0c;進行操作日志的Py解析達到效果 追蹤進程并寫入ssh操作到文件中 Ps: 此時機器A已經ssh登錄了機器B&#xff0c;取得它的ssh進程PID 機器A登錄后…

java h2 derby_嵌入式H2數據庫的Spring配置以進行測試

小編典典由于我不知道是否有任何工具可以檢查數據庫&#xff0c;我認為一個簡單的解決方案是使用支持HSQL&#xff0c;H2和Derby 的Spring嵌入式數據庫(3.1.x docs&#xff0c;current docs)。 。使用H2&#xff0c;你的xml配置如下所示&#xff1a;如果你更喜歡基于Java的配置…

基礎的python程序_Python程序入門

Python語法元素入門Python語法元素分析注釋注釋&#xff1a;程序員在代碼中加入的說明信息&#xff0c;不被計算機執行注釋的兩種方法&#xff1a;單行注釋以#開頭多行注釋以開頭和結尾# Here are the commentsThis is a multiline commerntused in Python縮進1個縮進 &#xf…

解決阿里云服務器磁盤報警

一般磁盤報警涉及到實際磁盤和inode文件索引節點 1.df -h檢查磁盤占用不高 2.df -i檢查inode文件索引節點有一個掛載目錄達到89%,里面有一個目錄產生大量的4k大的緩存文件,刪除該目錄下的文件解決: 刪除該目錄下小于4kb的文件 find /data/tmp -type f -size -4 -exec rm -rf {}…

leetcode310. 最小高度樹(bfs)

對于一個具有樹特征的無向圖&#xff0c;我們可選擇任何一個節點作為根。圖因此可以成為樹&#xff0c;在所有可能的樹中&#xff0c;具有最小高度的樹被稱為最小高度樹。給出這樣的一個圖&#xff0c;寫出一個函數找到所有的最小高度樹并返回他們的根節點。格式該圖包含 n 個節…

如何構建自己的免費無服務器評論框

by Shaun Persad通過Shaun Persad 如何構建自己的免費無服務器評論框 (How you can build your own free, serverless comment box) Contentful’s flexible content modeling goes far beyond blog posts. Here’s how you can leverage Contentful and Netlify to create a …

[Swift]LeetCode1035.不相交的線 | Uncrossed Lines

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★?微信公眾號&#xff1a;山青詠芝&#xff08;shanqingyongzhi&#xff09;?博客園地址&#xff1a;山青詠芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;?GitHub地址&a…

BZOJ1054(搜索)

大力搜&#xff0c;狀態用一個16位的數字表示。 1 #include <bits/stdc.h>2 3 using namespace std;4 5 #define rep(i,a,b) for(int i(a); i < (b); i)6 7 const int A 30 1;8 9 struct node{int x, y; } op[A]; 10 struct Nod…

php sql語句過濾,php如何做sql過濾

php如何做sql過濾SQL注入攻擊指的是通過構建特殊的輸入作為參數傳入Web應用程序&#xff0c;而這些輸入大都是SQL語法里的一些組合&#xff0c;通過執行SQL語句進而執行攻擊者所要的操作&#xff0c;其主要原因是程序沒有細致地過濾用戶輸入的數據&#xff0c;致使非法數據侵入…

ajaxfileupload 返回值_ajaxFileUpload上傳文件返回json無法解析

最近做一個文件上傳的功能&#xff0c;還要綁定數據傳輸到后臺&#xff0c;為了不影響前端的體驗&#xff0c;采用ajax發送請求。找了一些資料&#xff0c;網上的用ajaxupload這個插件。但是無論成功還是失敗都是執行的error的回調函數。后臺我采用springmvc返回的json&#xf…

leetcode133. 克隆圖(bfs)

給你無向 連通 圖中一個節點的引用&#xff0c;請你返回該圖的 深拷貝&#xff08;克隆&#xff09;。 圖中的每個節點都包含它的值 val&#xff08;int&#xff09; 和其鄰居的列表&#xff08;list[Node]&#xff09;。 class Node { public int val; public List neighbor…

OSCON上最受歡迎的Docker演講

本文講的是OSCON上最受歡迎的Docker演講&#xff0c;【編者的話】本文介紹了上個月OSCON大會有關Docker最受歡迎的一個分享&#xff1a;真實線上環境的Docker技巧。分享者是一名運維工程師叫Bridget&#xff0c;她所在的公司DramaFever在2013年10月開始在線上環境部署使用Docke…

測試驅動開發 測試前移_測試驅動開發:它是什么,什么不是。

測試驅動開發 測試前移by Andrea Koutifaris由Andrea Koutifaris Test driven development has become popular over the last few years. Many programmers have tried this technique, failed, and concluded that TDD is not worth the effort it requires.在過去的幾年中&…

【C/C++開發】C++庫大全

C特殊限定符(1)--static 當static來修飾類數據成員時&#xff0c;這個類的所有對象都可以訪問它。因為值在內存中持續存在&#xff0c;它可以被對象有效共享。這意味著當一個對象改變static數據成員的值時&#xff0c;就改變了所有對象的這個數據成員的值。 定義一個類: class …

java二維數組水平翻轉,C 語言 利用二維數組實現對輸入的數組進行翻轉

C 語言 利用二維數組實現對輸入的數組進行翻轉(幫助理解對圖像翻轉編輯原理)/*?輸入幾行幾列數字和翻轉方式&#xff0c;如&#xff1a;3 4 0即代表3行4列&#xff0c;左右翻轉&#xff1b;6 5 1即代表6行5列&#xff0c;上下翻轉。輸入示例&#xff1a;3 4 0________________…

lightgbm 保存模型 過大_一個例子讀懂LightGBM的模型文件

機器學習模型的可解釋性是個讓人頭痛的問題。在使用LightGBM模型的肯定對生成的GBDT的結構是好奇的&#xff0c;我也好奇&#xff0c;所以就解析一個LightGBM的模型文件看看&#xff0c;通過這個解析&#xff0c;你可以看懂GBDT的結構。另外&#xff0c;了解模型文件&#xff0…

Oracle Sql 胡亂記

/Oracle查詢優化改寫/ --1、coalesce 返回多個值中&#xff0c;第一個不為空的值 select coalesce(, , s) from dual; --2、order by -----dbms_random.value 生產隨機數,利用隨機數對查詢結果進行隨機排序 select * from emp order by dbms_random.value; --指定查詢結果中的一…

leetcode752. 打開轉盤鎖(bfs)

你有一個帶有四個圓形撥輪的轉盤鎖。每個撥輪都有10個數字&#xff1a; ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ 。每個撥輪可以自由旋轉&#xff1a;例如把 ‘9’ 變為 ‘0’&#xff0c;‘0’ 變為 ‘9’ 。每次旋轉都只能旋轉一個撥輪的一位…

Object Pools 噴泉效果實現

摘錄自&#xff1a;http://catlikecoding.com/unity/tutorials/object-pools/ 工程 效果圖 工程里面有響應的注釋 源碼我就不單獨放出來了

從頭學習計算機網絡_我如何通過從頭開始構建網絡爬蟲來自動進行求職

從頭學習計算機網絡它是如何開始的故事 (The story of how it began) It was midnight on a Friday, my friends were out having a good time, and yet I was nailed to my computer screen typing away.星期五是午夜&#xff0c;我的朋友們出去玩得很開心&#xff0c;但我被釘…