Checking whether a call to fmt.Errorf() failed [closed] - go

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In Go, the function fmt.Errorf() returns an error interface.
What's the proper way to check if fmt.Errorf() itself failed?

fmt.Errorf returns basically a string that is wrapped as an error. If you provide wrong arguments like in the following example, you still get an error but with the error message of the format fault inside the string message:
package main
import "fmt"
func main() {
fmt.Println(fmt.Errorf("abc", 5))
}
outputs the error string:
abc%!(EXTRA int=5)
These functions are not expected to be used in a context where you do not know the arguments that you are providing. The typical use case is that you "test" your formatting code when you write it. In your output code you will spot these error messages easily. You should just make sure to test these calls before going into production.
The danger of a panic in these functions is negligible, panics are caught as stated in the documentation:
If an Error or String method triggers a panic when called by a print routine, the fmt
package reformats the error message from the panic, decorating it with an indication
that it came through the fmt package. For example, if a String method calls
panic("bad"), the resulting formatted message will look like
%!s(PANIC=bad)

You should try to catch errors at compile and test time, not run time. For fmt.Errorf, run go vet.
For example,
package main
import "fmt"
func main() {
err := fmt.Errorf("%v")
fmt.Println(err)
}
Output:
$ go vet errorf.go
# command-line-arguments
./errorf.go:6: Errorf format %v reads arg #1, but call has 0 args
$
$ go run errorf.go
%!v(MISSING)
$
Command vet
Vet examines Go source code and reports suspicious constructs, such as
Printf calls whose arguments do not align with the format string. Vet
uses heuristics that do not guarantee all reports are genuine
problems, but it can find errors not caught by the compilers.
Vet is normally invoked using the go command by running "go vet":
go vet
Printf family
Flag: -printf
Suspicious calls to functions in the Printf family, including any
functions with these names, disregarding case:
Print Printf Println
Fprint Fprintf Fprintln
Sprint Sprintf Sprintln
Error Errorf
Fatal Fatalf
Log Logf
Panic Panicf Panicln
The -printfuncs flag can be used to redefine this list. If the
function name ends with an 'f', the function is assumed to take a
format descriptor string in the manner of fmt.Printf. If not, vet
complains about arguments that look like format descriptor strings.
It also checks for errors such as using a Writer as the first argument
of Printf.
Formatted output errors, by design, are a special case. For example, an error when reporting an error can be circular.
Package fmt
Format errors:
If an invalid argument is given for a verb, such as providing a string
to %d, the generated string will contain a description of the problem,
as in these examples:
Wrong type or unknown verb: %!verb(type=value)
Printf("%d", hi): %!d(string=hi)
Too many arguments: %!(EXTRA type=value)
Printf("hi", "guys"): hi%!(EXTRA string=guys)
Too few arguments: %!verb(MISSING)
Printf("hi%d"): hi%!d(MISSING)
Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi
Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
Invalid or invalid use of argument index: %!(BADINDEX)
Printf("%*[2]d", 7): %!d(BADINDEX)
Printf("%.[2]d", 7): %!d(BADINDEX)
All errors begin with the string "%!" followed sometimes by a single
character (the verb) and end with a parenthesized description.
If an Error or String method triggers a panic when called by a print
routine, the fmt package reformats the error message from the panic,
decorating it with an indication that it came through the fmt package.
For example, if a String method calls panic("bad"), the resulting
formatted message will look like
%!s(PANIC=bad)
The %!s just shows the print verb in use when the failure occurred. If
the panic is caused by a nil receiver to an Error or String method,
however, the output is the undecorated string, "".

Errorf formats according to a format specifier and returns the string
as a value that satisfies error. The fmt package's Errorf function lets us use the package's formatting features to create descriptive error messages.
func Errorf(format string, a ...interface{}) error {
return errors.New(Sprintf(format, a...))
}
And New returns an error that formats as the given text.
func New(text string) error {
return &errorString{text}
}
And errorString is a trivial implementation of error.
type errorString struct {
s string
}
So Basically what it is returning is field of string type.

Related

Won't print anything on terminal

I would like to know why when I execute the command go run example.go the won't print anything on terminal.
The code below works.
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
Will print Hello.
But when I would like to use the function fmt.Printf when I run the command to execute, appear very quickly the response but is deleted on terminal.
package main
import "fmt"
func main() {
var i int = 2
fmt.Printf("%v %T", i, i) // fmt.Print does not work to
}
You use fmt.Printf with a format that does not end with a newline, so your system dutifully prints out the output without a terminating newline.
Presumably your shell then overwrites the output by sending the cursor to the beginning of the line and printing something. To prevent this from happening, either have your program end its output with a newline, or update your shell's prompt to avoid printing over existing output.
(Side note: it's just Go, not Go Lang. This goes give some issues with searching, common among short-named languages like C and C++.)
When Printf is used, you need to put a \n at the end.
Your program will produce undefined: I.
By replacing I with i it should work https://play.golang.org/p/GxFh-SYePR3 and return 2 int.

Using cgo, why does C output not 'survive' piping when golang's does?

I'm experimenting with cgo to use C code from golang, but in my little hello-world test, I've ran into something I can't understand or find more information about.
I'm starting with a simple test similar to examples I've found
package main
import (
"fmt"
"unsafe"
)
/*
#import <stdio.h>
#import <stdlib.h>
*/
import "C"
func main() {
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
fmt.Printf("Printed from golang fmt\n")
}
This simple example just echoes strings to stdout from both golang (using fmt.Printf) and raw C (using C.puts) via the basic cgo binding.
When I run this directly in my terminal, I see both lines:
$ ./main
Printed from C.puts
Printed from golang fmt
When I run this but redirect output in any way – pipe to less, shell redirection to a file, etc – I only see golang's output:
./main | cat
Printed from golang fmt
What happens to the C.puts content when piping / redirecting?
Secondary questions: Is this a cgo quirk, or a c standard library quirk I'm not aware of? Is this behaviour documented? How would I go about debugging this on my own (e.g. is there a good/plausible way for me to 'inspect' what FD1 really is in each block?)
Update: If it's relevant, I'm using go version go1.6.2 darwin/amd64.
This is C behavior you're seeing.
Go does not buffer stdout, while in C it is usually buffered. When the C library detects stdout is a tty, it may use line buffering, so the additional \n inserted by puts will cause the output to be displayed.
You need to flush stdout to ensure you get all the output:
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
C.fflush(C.stdout)
fmt.Printf("Printed from golang fmt\n")
See also
Why does printf not flush after the call unless a newline is in the format string?
Is stdout line buffered, unbuffered or indeterminate by default?
The C library buffering is per line, so the first line can be left in the buffer before it is properly flushed (done at exit time in C programs). You can either try to flush stdout, or try adding a trailing \n in the first string. Does it work if you add the \n?

Control fmt.Parse output on Parsing Error

var timesFlag int
flag.IntVar(&timesFlag, "times", 1, "Number of times to print")
flag.Parse()
If I run the program and type in prog -times=abc (<--- not an int)
fmt.Parse spits out this ugly error message on the console:
invalid value "-abc" for flag -times: strconv.ParseInt: parsing "-abc": invalid syntax
Obviously, I can't prevent the user from typing in anything from the command line. The error looks like garbage to the user and needs to look more friendlier. How do I silent this error from going to stderr/stdout and detect there was an error generated?
The flag.CommandLine variable of type the FlagSet is used to handle command line arguments if you use the functions of the flag package which are not methods of the FlagSet type.
You can set the output (an io.Writer) where error messages are printed with the FlagSet.SetOutput() method. You can set a bytes.Buffer so messages will only end up in a buffer (and not on your console). Note that do not set nil as that means to print to the standard output (console).
And call FlagSet.Parse() yourself where you can pass os.Args[1:] as the arguments to be parsed. FlagSet.Parse() returns an error which you can handle yourself.

Emacs lisp; how to make a string from a variable of any type?

Like error messages for wrongly called functions show, eg.:
(message (file-attributes "."))
Produces the message:
"eval: Wrong type argument: stringp, ("/home14/tjones" 1 0 0 (20415 35598) (20211 19255) (20211 19255) 14 "lrwxrwxrwx" t ...)"
How do you do this type of translation intentionally, eg.:
(message (thing-to-string (file-attributes ".")))
To message something like:
("/home14/tjones" 1 0 0 (20415 35598) (20211 19255) (20211 19255) 14 "lrwxrwxrwx" t ...)
This is for debugging/info only. I'm assuming there's a way as message is doing it, but is this exposed to us users?
Look into prin1-to-string and related functions (prin1, princ, etc). And do try the manual! http://www.gnu.org/software/emacs/manual/html_node/elisp/Output-Functions.html
In your example, message did not do anything (it just refused to run), so the translation to string was done by the read-eval-print loop which caught the error and turned it into a text message.
But yes, message can also do that, and it does that by calling format, which internally uses things like prin1-to-string.
So (format "%S" <foo>) would do your thing-to-string.
The first argument to message is supposed to be a format string (same as the one you pass to the format function. If you give it the format "%s" (or "%S" as in Stefan's answer.) it will stringify anything you give it as the next argument.
The capital S version will escape characters in the string so that it can be read again as an s-expression. In this case, I think that is what you want. So, you don't need to change your code very much to get what you are looking for:
(message "%S" (file-attributes "."))

How to cast a function name to an address and add offset in LLDB?

Say, I have two adjacent functions subfunc() and main() in the Mach-O executable and want to disassemble all instructions from subfunc() to main()+0x10.
I know I can cast functions to addresses using `(void(*)())subfunc` - isn't there an easier way?
My attempt is as follows, but I get the error message below:
dis -s `(void(*)())subfunc` -e `(void(*)())main+0x10`
error: error: arithmetic on a pointer to the function type 'void ()'
How can I fix this?
This appears to be the correct syntax:
dis --start-address `(void(*)())main` --end-address `(void(*)())main`+0x10
The very small difference between this syntax and the variant you tried is that the +0x10 offset goes outside the backtick characters, i.e. the offset goes after the closing backtick.
FWIW this variant also appears to work correctly:
dis --start-address `(void(*)())main` --end-address 0x10+`(void(*)())main`
Discovery process:
I was unfamiliar with the "backtick" + function cast that you described in your original question so that was a very helpful starting point.
In my case I was trying to set a breakpoint at a function offset inside a shared library and got about as far as this before my search landed me on your question:
breakpoint set --shlib libexample.dylib --address `((void*)some_function)+81`
error: error: function 'some_function' with unknown type must be given a function type
error: 1 errors parsing expression
The use of your function cast hint met the "function type" requirement stated in the error message so I was next able to get to:
print (void(*)())some_function
(void (*)()) $38 = 0x00000001230094d0 (libexample.dylib`some_function)
I then tried the backtick variant which appeared to work but I wanted the value to be displayed in hexadecimal:
print `(void(*)())some_function`
(long) $2 = 4882207952
But when I tried to use the -f hex format option with print I got an error:
print -f hex `(void(*)())some_function`
error: use of undeclared identifier 'f'
error: 1 errors parsing expression
Eventually I noticed the comment 'print' is an abbreviation for 'expression --' at the bottom of the help print output and realised that means it's (apparently?) not possible to use an alternative display format with print because it gets converted into expression -- -f hex ... which is not valid syntax.
Eventually I figured out the required placement & combination of command name, display format and "--" to make it display as desired:
expression -f hex -- `(void(*)())some_function`
(long) $7 = 0x00000001230094d0
For no particular reason (that I can remember) it was at this point I tried placing the offset outside the backticks and it worked!
expression -f hex -- `(void(*)())some_function`+81
(long) $12 = 0x0000000123009521
And it still worked when I tried it with a breakpoint:
breakpoint set --shlib libexample.dylib --address `(void(*)())some_function`+81
Breakpoint 6: where = libexample.dylib`some_function + 81, address = 0x0000000123009521
Then I verified that it also worked with the dis command from your original question:
dis --start-address `(void(*)())some_function` --end-address `(void(*)())some_function`+81
And confirmed that the bare function name was not sufficient:
dis --start-address some_function --end-address `(void(*)())some_function`+81
error: address expression "some_function" evaluation failed
I also re-confirmed that the offset being between the backticks did not work:
dis --start-address `(void(*)())some_function` --end-address `(void(*)())some_function+1`
error: error: arithmetic on a pointer to the function type 'void ()'
error: 1 errors parsing expression
It was at this point that I realised I was able to parse the error message (as it was presumably intended):
[arithmetic on a pointer] [to the function type] ['void ()']
The underlying issue being "arithmetic on a pointer"...
Which further research shows is both "undefined on pointers to function types" and available as a gcc extension:
https://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html
Why is it not allowed to perform arithmetic operations on function pointers?
Should clang and gcc produce a diagnostic message when a program does pointer arithmetic on a function pointer?
Incrementing function pointers
Function pointer arithmetic
How to print the address of a function?
https://github.com/llvm/llvm-project/blob/f804bd586ee58199db4cfb2da8e9ef067425900b/clang/test/Sema/pointer-addition.c
https://reviews.llvm.org/D37042
Which brings us back to the comments by #JasonMolenda & #JimIngham and how the function pointer arithmetic parsing is special-cased.
To my mind the "error: arithmetic on a pointer to the function type..." message you received is at best poor UX & at worst a bug--given that lldb itself essentially displays address references in that manner:
0x1230094f9: jle 0x123009cc2 ; some_function + 2034
I feel similarly about libexample.dylib`some_function + 81 being displayed but AFAICT not being parsed.
In conclusion, this form works:
`(void(*)())some_function`+0x10
Now I just need to figure out why some_function isn't doing what I think it should... :)

Resources