mirror of
https://github.com/kataras/iris.git
synced 2025-12-18 10:27:06 +00:00
add some MVC error handle examples
This commit is contained in:
60
_examples/mvc/error-handler-hijack/main.go
Normal file
60
_examples/mvc/error-handler-hijack/main.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris/v12"
|
||||
"github.com/kataras/iris/v12/mvc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.RegisterView(iris.HTML("./views", ".html"))
|
||||
|
||||
// Hijack each output value of a method (can be used per-party too).
|
||||
app.ConfigureContainer().
|
||||
UseResultHandler(func(next iris.ResultHandler) iris.ResultHandler {
|
||||
return func(ctx iris.Context, v interface{}) error {
|
||||
switch val := v.(type) {
|
||||
case errorResponse:
|
||||
return next(ctx, errorView(val))
|
||||
default:
|
||||
return next(ctx, v)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
m := mvc.New(app)
|
||||
m.Handle(new(controller))
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
|
||||
func errorView(e errorResponse) mvc.Result {
|
||||
switch e.Code {
|
||||
case iris.StatusNotFound:
|
||||
return mvc.View{Code: e.Code, Name: "404.html", Data: e}
|
||||
default:
|
||||
return mvc.View{Code: e.Code, Name: "500.html", Data: e}
|
||||
}
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
|
||||
type controller struct{}
|
||||
|
||||
type user struct {
|
||||
ID uint64 `json:"id"`
|
||||
}
|
||||
|
||||
func (c *controller) GetBy(userid uint64) interface{} {
|
||||
if userid != 1 {
|
||||
return errorResponse{
|
||||
Code: iris.StatusNotFound,
|
||||
Message: "User Not Found",
|
||||
}
|
||||
}
|
||||
|
||||
return user{ID: userid}
|
||||
}
|
||||
12
_examples/mvc/error-handler-hijack/views/404.html
Normal file
12
_examples/mvc/error-handler-hijack/views/404.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Client Error Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>{{.Code}}</h2>
|
||||
<h3>{{.Message}}</h3>
|
||||
</body>
|
||||
</html>
|
||||
12
_examples/mvc/error-handler-hijack/views/500.html
Normal file
12
_examples/mvc/error-handler-hijack/views/500.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Server Error Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>{{.Code}}</h2>
|
||||
<h3>{{.Message}}</h3>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user