When I use ioutil
to read a file, it may return an error. But if I want to filter some error code, what should I do?
res, err := ioutil.ReadFile("xxx")
if err != nil {
fmt.Println(err.Error())
}
...
In the code snippet above, when a file has no permission, fmt.Println(err.Error())
will print "open xxxxx: permission denied
.
If I want to capture this kind error, how can I know that file read failed because permission was denied?
Should I search err.Error()
for the string permission denied
- this looks ungraceful. Is there any better way?
Thanks in advance.
Update
After trying @Intermernet solution, I found that it will not hit case os.ErrPermission
, it will hit default
and print "open xxx: Permission denied"
.
@Aedolon solution is ok, os.IsPermission(err)
can tell that a file has failed with permission deny.