ExSlop.Check.Refactor.TryRescueWithSafeAlternative (ExSlop v0.3.1)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of high and works with any version of Elixir.

Explanation

try/rescue around a function that has a non-raising equivalent is a sign the AI doesn't know Elixir's API.

# bad
try do
  String.to_integer(value)
rescue
  _ -> nil
end

# good
case Integer.parse(value) do
  {int, ""} -> int
  _ -> nil
end

Common pairs:

RaisingSafe alternative
String.to_integer/1Integer.parse/1
String.to_float/1Float.parse/1
String.to_atom/1String.to_existing_atom/1
Jason.decode!/1Jason.decode/1
JSON.decode!/1JSON.decode/1
Map.fetch!/2Map.fetch/2
Keyword.fetch!/2Keyword.fetch/2
Enum.fetch!/2Enum.fetch/2 / Enum.at/2
File.read!/1File.read/1
File.write!/2File.write/2
URI.parse/1 (old)URI.new/1

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.