Custom error types

V gives you the ability to define custom error types through the IError interface. The interface requires two methods: msg() string and code() int. Every type that implements these methods can be used as an error.

When defining a custom error type it is recommended to embed the builtin Error default implementation. This provides an empty default implementation for both required methods, so you only have to implement what you really need, and may provide additional utility functions in the future.

  1. struct PathError {
  2. Error
  3. path string
  4. }
  5. fn (err PathError) msg() string {
  6. return 'Failed to open path: $err.path'
  7. }
  8. fn try_open(path string) ? {
  9. return IError(PathError{
  10. path: path
  11. })
  12. }
  13. fn main() {
  14. try_open('/tmp') or { panic(err) }
  15. }