Last active
February 5, 2018 14:36
-
-
Save atotto/6960403 to your computer and use it in GitHub Desktop.
golang panic-recover example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example | |
import ( | |
"fmt" | |
"reflect" | |
) | |
func ExamplePanic() { | |
err := Counter("hoge") | |
fmt.Println(err) | |
// You can get the type of error value | |
fmt.Println(reflect.ValueOf(err).Type()) | |
// You can use type switch | |
switch err.(type) { | |
case *UnsupportedStateError: | |
fmt.Println("Unsupported State Error!!") | |
default: | |
} | |
// Output: | |
// example: unsupported state: hoge | |
// *example.UnsupportedStateError | |
// Unsupported State Error!! | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2013 The Go Authors. All rights reserved. | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
// 一度panicにしてrecoverする | |
// 深い階層で発生したエラーを処理する場合に便利 | |
// Exceptionのような使い方ができる | |
package example | |
import ( | |
"fmt" | |
"runtime" | |
) | |
// Counter 外部API | |
func Counter(str string) error { | |
s := &state{} | |
err := s.counter(str) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
type state struct { | |
count int | |
} | |
type UnsupportedStateError struct { | |
string | |
} | |
func (e *UnsupportedStateError) Error() string { | |
return "example: unsupported state: " + e.string | |
} | |
// | |
func (s *state) error(err error) { | |
panic(err) | |
} | |
// | |
func (s *state) String() string { | |
return fmt.Sprintf("%v", s) | |
} | |
func (s *state) counter(str string) (err error) { | |
// ここでrecoverする | |
// 内部でruntime.Errorとなったものはそのままpanicになる | |
defer func() { | |
if r := recover(); r != nil { | |
if _, ok := r.(runtime.Error); ok { | |
panic(r) | |
} | |
err = r.(error) | |
} | |
}() | |
// ここでは単にに3文字以上はエラーとする | |
if len(str) > 3 { | |
s.error(&UnsupportedStateError{str}) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment