prefer_implicit_try.ex (1624B)
1 defmodule Credo.Check.Readability.PreferImplicitTry do 2 use Credo.Check, 3 base_priority: :low, 4 explanations: [ 5 check: """ 6 Prefer using an implicit `try` rather than explicit `try` if you try to rescue 7 anything the function does. 8 9 For example, this: 10 11 def failing_function(first) do 12 try do 13 to_string(first) 14 rescue 15 _ -> :rescued 16 end 17 end 18 19 Can be rewritten without `try` as below: 20 21 def failing_function(first) do 22 to_string(first) 23 rescue 24 _ -> :rescued 25 end 26 27 Like all `Readability` issues, this one is not a technical concern. 28 The code will behave identical in both ways. 29 """ 30 ] 31 32 @def_ops [:def, :defp, :defmacro] 33 34 @doc false 35 @impl true 36 def run(%SourceFile{} = source_file, params) do 37 issue_meta = IssueMeta.for(source_file, params) 38 39 Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta)) 40 end 41 42 # TODO: consider for experimental check front-loader (ast) 43 for op <- @def_ops do 44 defp traverse( 45 {unquote(op), _, [{_, _, _}, [do: {:try, meta, _}]]} = ast, 46 issues, 47 issue_meta 48 ) do 49 line_no = meta[:line] 50 51 {ast, issues ++ [issue_for(issue_meta, line_no)]} 52 end 53 end 54 55 defp traverse(ast, issues, _issue_meta) do 56 {ast, issues} 57 end 58 59 defp issue_for(issue_meta, line_no) do 60 format_issue( 61 issue_meta, 62 message: "Prefer using an implicit `try` rather than explicit `try`.", 63 trigger: "try", 64 line_no: line_no 65 ) 66 end 67 end